lua-users home
lua-l archive

Re: Re: How to call functions inside a table from C?

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It works! Thank you.
Here is my code:
void ScriptInterface::CallTableFunction(char* tableName, char *funcName)
{
int TableIndex = 0;
lua_getglobal(L,tableName);
TableIndex = lua_gettop(L);
lua_getfield(L,TableIndex,funcName);
if(lua_pcall(L, 0, 0, 0) != 0)
{
cout << "Erro ao chamar função: "
<< lua_tostring(L, -1)
<< endl;
}
lua_settop(L, TableIndex - 1);
}
Link Hughes wrote: >
Been doing this a lot lately.
You just need to get the function onto the stack so that you can use a
lua_pcall() on it and any appropriate arguments.
So first you need to get the table that the function is in. Personally,
I also like to note the stack index of the table when I do something
like this since it makes the code more readable and helps with clean-up.
 int MinhaTabela;
 lua_getglobal( L, "MinhaTabela" );
 MinhaTabela = lua_gettop( L );
Then you'll need to get the function into the stack as well.
 lua_getfield( L, MinhaTabela, "variosCirculos2" );
Then, finally, push any arguments and make the call.
 if ( lua_pcall( L, 0, 0, 0 ) != 0 ) { /* Error Handling */ }
And if you have the table's index, then cleaning up the stack is easy
because you don't have to remember how many elements to pop.
 lua_settop( L, (MinhaTabela - 1) );
In your case, it looks like you'll need a new C function for calling Lua
functions resident in tables, so you'd need something like:
 void ScriptInterface::CallTableFunction(int tableIdx, char *funcName)
 {
 lua_getfield( L, tableIdx, funcName );
 if ( lua_pcall( L, 0, 0, 0 ) != 0 ) { /* Error Handling */ }
 }
Hope that helps.
-Link
--
Link Hughes
Lead Programmer
1st Playable Productions
http://www.1stplayable.com
Edmar wrote:
**Sorry for my bad English. **
Good day.
I'm trying to call a function declared inside a lua table, from my
code in "C". This is my lua code:
MinhaTabela=
{
textos =
{
 textoSair = "Aperter ESC para sair a qualquer momento",
 textoEnter = "Aperte enter para jogar"
},
variosCirculos2 =
function ()
 for X=1, 30 do Circulo(X * 10,X * 10,X * 5,X * 10,X * 5,0); end
 Atualizar();
end,
relogio =
function ()
 ty = ty + 2;
 tx = tx + 5;
end
}
So, how can I call the functions 'variosCirculos2" or "relogio" from
C? This is the code that I use to call Lua functions:
void ScriptInterface::CallFunction(char *funcName)
{
lua_getglobal(L, funcName);
if(lua_pcall(L, 0, 0, 0) != 0)
{
cout << "Erro ao chamar fun??o: "
<< lua_tostring(L, -1)
<< endl;
}
}
Thanx for the atention.

AltStyle によって変換されたページ (->オリジナル) /