-
Notifications
You must be signed in to change notification settings - Fork 2
Example 2: Reading a Lua Table
kamih edited this page Jul 14, 2012
·
1 revision
Lua uses what it calls tables to define all sorts of data structures.
Here is table.lua, which contains one table that acts as both a map and an array:
TableVal =
{
-- Add some mapped values
BoolVal = true,
FloatVal = 23.42,
StringVal = "awesome table!",
-- Add some array values
12.42,
16.34,
18.73,
21.23
}
This is how you would read its values with LuaUtils in C++:
using namespace LuaUtils;
// Create a new LuaState and load the table.lua file
LuaState state;
state.loadFile("table.lua");
// Read the table
LuaTable table;
state.getValue("TableVal", table);
// Read its mapped values
float fval;
bool bval;
std::string sval;
table.getValue("BoolVal", bval);
table.getValue("StringVal", sval);
table.getValue("FloatVal", fval);
// Read its array values
std::vector<float> values;
for (size_t i = 1, sz = table.getArraySize(); i <= sz; ++i)
{
table.getValue(i, fval);
values.push_back(fval);
}
As you can see, the same convenient getValue function is available for LuaTable objects. But you can also access the table’s array elements by passing an integer index to this function, and using LuaTable::getArraySize to get the number of elements. By default, the starting Lua table array index is 1, so be careful to index the array correctly.
You can also set table values by calling LuaTable::setValue.