Page 1 of 1

Howto: expand variable

Posted: Sat Aug 22, 2009 3:22 am
by eraldo
How do I get a number from a string which is the name of a variable ...not a stringed number?

Example:

Global variable:
MyNumber = 10

function:

Code: Select all

    testFunction(a, b)
        local VariableNameString = a .. b
        local value = tonumber( VariableNameString )
        echo( value )
    end
Function call:
testFunction( "My", "Number" )

Wanted Echo Result:
10

>> Got an Wrong Argument Error

I am lacking some sort of expandVariable(variable) function...

Code: Select all

    testFunction(a, b)
        local VariableNameString = a .. b
        local value = expandVariable( VariableNameString )
        echo( value )
    end
How can I solve this?
Any ideas?
Many thanks,
Eraldo

Re: Howto: expand variable

Posted: Sat Aug 22, 2009 4:26 am
by eraldo
Solved it like this:

function expand(variable)
return _G[variable]
end

This could be of general interest!

Greetings,
Eraldo

Re: Howto: expand variable

Posted: Sat Aug 22, 2009 5:21 am
by Caled
That is definitely of interest. I'll have to play with that myself first, but if it is doing what it looks like it is doing, then it is a nice solution. I've been using tables when I need recursion, thinking that it is impossible with a simple variable.

Re: Howto: expand variable

Posted: Sat Aug 22, 2009 9:15 am
by Heiko
The table _G is the so called global variable table in Lua. All variables, tables and functions are stored in this table.