lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


spam@bitlet.com wrote:
> I'm trying to expand some existing LUA code in a project. Below is a
> simplified version of an existing function to explain what I'm after: 
> 
>  const foo = 4
> 
>  function compare_value(a,b)
>   return a == b
>  end
> 
> [...]
> 
> What I want to do is translate variable "a" from the string "foo"
> into its equivalent named variable value of "4", so that: 
> 
>  compare_label("foo",4)
> 
> is true.

I see two possibilities:
-- 1. Put constants in a table
local const = {
    foo = 4
}
function compare_label(a,b)
    return const[a]==b
end

-- 2. Use the global table to hold the constants
foo = 4
function compare_label(a,b)
    return _G[a]==b
end

Note that the second example implies that foo is global. If foo is
local, you can't reliably access its name at runtime.