Call a function in Lua and get the return value in C++
How do I get data from a Lua
script in C++ code? As I understand it, the data exchange from the script to the pros goes through a special LUA-Стек
. Help me understand, let's say there is such a very useful function on Lua
:
function add( x, y )
return x + y
end
In C++, here is the code:
#include "stdafx.h"
extern "C" {
#include "Lua\lua.h"
#include "Lua\lauxlib.h"
#include "Lua\lualib.h"
}
lua_State* L = NULL;
int from_lua_add(int x, int y)
{
int sum;
lua_getglobal(L, "add");
lua_pushnumber(L, x);
lua_pushnumber(L, y);
lua_call(L, 2, 1); /* Ошибка */
sum = (int)lua_tointeger(L, -1);
lua_pop(L, 1);
return sum;
}
int main()
{
L = lua_open();
luaL_openlibs(L);
luaL_dofile(L, "script.lua");
int summ;
summ = from_lua_add(1, 1);
printf("the summ from lua is %d\n", summ);
lua_close(L);
getchar();
return 0;
}
On the call lua_call
, a crash occurs, an error of the following content:
Unprotected error in call to lua api (attempt to call a nil value)
What did I do wrong ?
2 answers
Code examples can be found here: http://lua-users.org/wiki/SampleCode There is a long example of working with Lua from C++ here: http://lua-users.org/wiki/CallingLuaFromCpp
Here is a short example of getting data from Lua to C. The difference from C++ is small.
Http://lua-users.org/wiki/GettingValuesFromLua
Example code for Lua 5.1.1:
Returnone.c:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main()
{
lua_State *L = luaL_newstate();
char buff[] = "return 1,'a'";
int error;
printf( "%d\n", lua_gettop(L) );
error = luaL_loadbuffer(L, buff, strlen(buff), "my test") || lua_pcall(L, 0, LUA_MULTRET, 0);
if (error) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1); /* pop error message from the stack */
}
printf( "%d\n", lua_gettop(L) );
printf( "%s\n", lua_tostring(L,-2) );
printf( "%s\n", lua_tostring(L,-1) );
return 0;
}
What did I do wrong ?
You completely ignored the error handling in your code.
The luaL_dofile
function returns a response code that should be analyzed (surprise!), and not just ignored. The same applies to lua_getglobal
and so on.
If you add this kind of processing to compile and run the script:
int err = luaL_dofile(L, "script.lua");
if (err) {
printf("Cannot dofile: %s", lua_tostring(L, -1));
lua_pop(L, 1);
return 1;
}
Then if the script file is suddenly not found, a message will be displayed:
Cannot dofile: cannot open script.lua: No such file or directory
Also, any syntax errors in the the script itself, if it is suddenly written with errors.
If this processing is removed, then if the file script.lua
is unavailable, a message will be displayed as in your question.