Skip to main content
GameDev.net gamedev.net
🔒 Locked

Lua: How to get variables.

Started by madmaurice Jan 5, 2008 at 2:44 PM 7 replies 2.2k views
Original Post
madmaurice
madmaurice
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.
Hidden Asbestos
Hidden Asbestos
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.
madmaurice
madmaurice
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;}
madmaurice
madmaurice
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
madmaurice
madmaurice
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.
_the_phantom_
_the_phantom_
being able to see the .Lua file AND the C or C++ code which sets it up and calls it would be useful as well, right now we can't tell what is going on...
madmaurice
madmaurice
forgot to say that i solved it.

the lus file was in the wrong folder.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.