Using variables in LUA

Hi @RickCarlino ,

I’d like to use my soil moisture readings in an LUA assert block. How can I do that? The idea is that I will check the garden moisture, then decide to water based on the soil sensor all in one sequence.

@stre1026 Have you already tried something like this?:

reading, error = read_pin(54, "analog")

if error then
  send_message("error", inspect(error), "toast")
  return false
  send_message("info", inspect(reading), "toast")
  return reading > 100

Hey @RickCarlino

I haven’t. Is there a way to store the readings from my moisture sensor sequence and then access that variable separately using this? I know we’ve been down this road before in other threads, but I’m wondering if anything has changed?

@stre1026 We’ve not added that feature in this release. Couldn’t you do something like this, though?:

-- First, pull up any old data that might be
-- stored in `env()`:
old = env("readings")

if old then
    -- If there is old data on this account,
    -- decode the JSON data.
    data = json.decode(old)
    -- If no data was found, initialize an empty
    -- data structure.
    data = {size = 0, list = {}}

-- Perform a new sensor reading.
reading = read_pin(13, "analog")

-- Add the newest reading to the data structure that
-- stores old readings.
data.size = data.size + 1
data.list[data.size] = reading

-- Inspect the output in a toast pop-up:
send_message("info", "Sensor readings: " .. inspect(data.list), "toast")

-- Finally, save the data back to `env()`:
env("readings", json.encode(data))

Example output:


Hey @RickCarlino

That’s pretty cool. I hadn’t thought of (and didn’t realize you could) use arrays, etc. in LUA code. I’ll have to play with this. Pretty neat.

Glad that helps! One thing to keep in mind about Lua arrays is that they are much more minimal than arrays in languages like Ruby, Python, JS etc… They are essentially hash tables with numeric indexes. This means that operations like push() and pop() require some extra glue code, as you can see with my use of the size attribute in the example above. It’s not uncommon to see folks accidentally create “holes” in their arrays or overwrite the wrong value if they lose track of the array size or current index.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.