Sign in to follow this  

Lua: How to get variables.

This topic is 3623 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

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

This topic is 3623 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this