Howto: expand variable

Post Reply
eraldo
Posts: 43
Joined: Sun Jul 12, 2009 1:25 am

Howto: expand variable

Post 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
Last edited by eraldo on Sat Aug 22, 2009 4:27 am, edited 1 time in total.

eraldo
Posts: 43
Joined: Sun Jul 12, 2009 1:25 am

Re: Howto: expand variable

Post by eraldo »

Solved it like this:

function expand(variable)
return _G[variable]
end

This could be of general interest!

Greetings,
Eraldo

Caled
Posts: 403
Joined: Thu Apr 09, 2009 4:45 am

Re: Howto: expand variable

Post 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.

User avatar
Heiko
Site Admin
Posts: 1548
Joined: Wed Mar 11, 2009 6:26 pm

Re: Howto: expand variable

Post by Heiko »

The table _G is the so called global variable table in Lua. All variables, tables and functions are stored in this table.

Post Reply