• Advertisement
Sign in to follow this  

Lua: How to get variables.

This topic is 3689 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

is there any chance to get the value of a variable that is defined in lua code after running it? like: - open *.lua file - running code - getting value of variable xy.

Share this post


Link to post
Share on other sites
Advertisement
Hi, I'm no Lua expert but basically the procedure is something like:


bool GetGlobalNumber( lua_State* p_lua, const char* p_name, lua_Number& number )
{
// Put the value onto the stack.
lua_getglobal( p_lua, p_name );

bool result = false;

// Is the top of the stack a number?
if ( lua_isnumber( p_lua, -1 ) )
{
number = lua_tonumber( p_lua, -1 );
result = true;
}

// pop it off the stack now we're done
lua_pop( p_lua, 1 );

return result;
}

void main()
{
... load script & execute

lua_Number num;
if ( GetGlobalNumber( p_lua, "xy", num ) )
{
printf( "%f\n", num );
}
}


This is a very simple example. I've just finished writing my second VM interface (this time using Squirrel which is quite similar) and I've made improvements to my architecture by creating a general "VMValue" object which is capable of holding any type of data - instead of using lua_isnumber, I now use the equivalent of lua_type to determine what storage is required and have this general purpose value class handle it.

This has allowed me to replace loads of naively duplicate functions with a few general calls like GetGlobal( lua_State*, VMValue& ). But I guess that's getting a bit ahead of things - Anyway, I hope my basic example helps point you in the right direction to begin with.

Share this post


Link to post
Share on other sites
i tried this but i always get 0 after i ran the file.

int lua_getInt(lua_State* L, const char* var) {
int result;
lua_getglobal(L,var);
result =(int)lua_tonumber(L,-1);
lua_pop(L,1);
return result;
}

Share this post


Link to post
Share on other sites
it works.
however i get 0 when
parsing "a = 11*3" although i init math lib.
is this normal?

edit: lua_isnumber(l,-1) is false

Share this post


Link to post
Share on other sites
What did you pass to lua_getInt()?

lua_State and var name

Or better yet, show the code.

look at my posts i already posted my getInt function.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement