Question
Lua Infotables
Reposting Mike Mahoney's blog post:
"The 5.0 version of the Lua script resource has improved support for InfoTables. By using the tw_infotable library you can create and manipulate InfoTables:
--
-- Create a DataShape. This definition will place the DataShape into
-- the global 'DataShape' table. This definition would typically be
-- found in your template file.
--
dataShapes.MeterReading(
{ name = "Temp", baseType = "INTEGER" },
{ name = "Amps", baseType = "NUMBER" },
{ name = "Status", baseType = "STRING", aspects = {defaultValue="Unknown"} },
{ name = "Readout", baseType = "TEXT" }
)
-- Lock around this chunk of code. Must always lock around
-- access to the global DataShape table.
tw_mutex.lock()
--
-- Access the DataShape we want to use and then clone it. DataShapes
-- must always be cloned before being used to create an InfoTable.
--
local ds = DataShape.MeterReading:clone()
--
-- Create an InfoTable based on the DataShape. If this fails the
-- function will return nil plus an error message.
--
local it, err = tw_infotable.createInfoTable(ds)
--
-- Add a row to the new InfoTable. The keys in the row must match te field names
-- in the DataShape. This will return a nil and an error message on failure.
--
local s, msg = it:addRow({Temp = 65, Amps = 10, Status = "OK", Readout = "Ready"})
--
-- You can access a value from a row using getValueFromRow()
--
local amps = it:getValueFromRow("Amps", 0)
--
-- Convert an InfoTable to a Lua table.
--
local itTable = it:toTable()
--
-- Encode the InfoTable into a string of JSON.
--
local itStr = json.encode(itTable)
--
-- Make sure to unlock. If your code does error checking and returns in other
-- places, make sure to unlock before each return.
--
tw_mutex.unlock()
"
