Counter that increments with a button click?

This is probably a very simple question, but I am really struggling to get my head around it at the moment.

How do I set up a simple integer variable (local to a page) that increments by 1 each time I press a button (on the same page)? It should be something I can put into my daily journal template, so that each day I have a counter starting at 0 that I can use to track quotas for different things.

I would also like to keep track of multiple counters in a single table (where a different button increments each counter) if possible, but I want to at least get one counter working first.

Save the counter to a file.

If you wanna read it, read it from the file.

If you want to increment it, read it from file, increment it, write it back to file.

Edit: this will get somewhat annoying when you run into conflicts. Just saying :wink:

How would I do this in Space Lua?

I’m wanting to have a separate counter for each day (I have a different page for each day in a Daily folder), having a second file just for the counter for each day doesn’t seem like the best way to go about this.

basic example

-- number - the count
-- id - unique number per counter to support multiple counters on a page
function counter(number, id)
  local stringNumber = tostring(number)
  return widgets.button(stringNumber, function()
    local text = editor.getText()
    local start, end_ = string.find(text, "${counter(" .. number .. ", " .. id .. ")}", 1, true)
    number = number + 1
    if (start and end_) then
      editor.replaceRange(start, end_, "{counter(" .. number .. ", " .. id .. ")}" )
    end
  end)
end

use with

${counter(0, 0)}

on any page

1 Like

Would be interesting if we could get the position of the widget on the page in the widgets global enviornment? Should be fairly easy to provide that right?

Thank you.

How would I set this up so that the counter text isn’t part of the button itself?

Something like a table of counters, e.g.:

Counter A Counter B
0 / 10 5 / 10

And then a separate button for each counter (like “Counter A +1” or “Increment Counter B”) that would increase the numbers in the table accordingly?

I’m aware I can just edit the text myself, but also… buttons!

I thought it might be possible to (ab)use the config for this:

function counter(number, name)
  local id = 'counters.' .. name
  local count = config.get(id, number)
  return widgets.button(count .. '', function()
    config.set(id, count + 1)
    editor.invokeCommand('System: Reload')
  end)
end

But for some reason it doesn’t update inside the callback. Maybe a bug?
If I increment it outside the callback, it works everytime the button is rendered (counter(..., ...) is called).

It does work with localStorage, but then it won’t work across clients.