Dynamic variable names in Lua

posted in: code, Dev Blog, tutorials | 0

When scripting it’s often necessary to get the name of a variable from the data file in order to set it. The Lua manual suggests using the construct

value = _G[varname]

This doesn’t work when the variable name is part of a table, i.e. for example:

value = _G[data] works, but

value = _G[data.fish.size] just returns nil because it’s trying to use “data.fish.size” as a table key in the global table

In order to address the problem, the manual provides an example function getfield which doesn’t work. What does work is adapting the code for setfield, as follows:

function getfield (f)

  local t = _G — start with the table of globals
  local v = nil
  for w, d in string.gfind(f, “([%w_]+)(.?)”) do
    if d == “.” then — not last field?
      t[w] = t[w] or {} — create table if absent
      t = t[w] — get the table
    else — last field
      v = t[w] — do the assignment
  return v;

(this stems from looking at the load/save issues Corona has even with the examples provided on the web which failed to work for me)