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
else
  send_message("info", inspect(reading), "toast")
  return reading > 100
end

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)
else
    -- If no data was found, initialize an empty
    -- data structure.
    data = {size = 0, list = {}}
end

-- 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))
3 Likes

Example output:

image

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