Learn Lua · Your first CoCoCo script · Lesson 3 of 3

Calling CoCoCo

ctx functions reach the rest of CoCoCo: the database, devices, stored records and more. Functions that have to wait for something return two values: ok, and then the result when ok is true or the error message when it is false.

LUA
-- local ok, record = ctx.store.get("counter")
-- if not ok then error(record, 0) end

These lines are comments because ctx is only there when CoCoCo runs the script. In this lesson, the checks stand in for it. Check with if not ok then: after that check, the editor knows that record holds the result rather than an error message.

ctx.store keeps small named records for a custom app or an integration. ctx.store.get(name) gives the record (with your values in its data field), or nil if there isn't one yet. ctx.store.put(name, data) saves one. Always check ok before you use the result: Calling CoCoCo explains why.

Steps

  1. Read the record "counter" and return previous: its data.count, or 0 when there is no record yet.
  2. Save { count = previous + 1 } as "counter" and return that number as count.
  3. When reading fails (ok is false), stop with an error that includes the message you got.
Show a hint

Deal with not ok first, so the rest of the code only runs when reading worked. A missing record is nil with ok still true, so check record ~= nil before reading its data.