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.
-- local ok, record = ctx.store.get("counter")
-- if not ok then error(record, 0) endThese 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
- Read the record
"counter"and returnprevious: itsdata.count, or 0 when there is no record yet. - Save
{ count = previous + 1 }as"counter"and return that number ascount. - When reading fails (
okisfalse), 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.