I want to call an external lua_5.2 function from C, so I made a minimal example to try it out.
The minimal testfile:
--- filename: play.lua
function hello()
print("Hello World!\n")
end
Trying to call this function from C:
#include <stdio.h>
#include <stdlib.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
int
main(void) {
lua_State *L;
int status;
int result;
L = luaL_newstate();
luaL_openlibs(L);
status = luaL_loadfile(L, "play.lua");
if (status != LUA_OK) {
fprintf(stderr, "Could not load 'play.lua'!");
exit(1);
}
lua_getglobal(L, "hello");
if (lua_isfunction(L, -1)) {
fprintf(stderr, "ERROR: Not a function!\n");
exit(1);
}
result = lua_pcall(L, 0, 0, 0);
if (result!= LUA_OK) {
fprintf(sterr, "Error running lua: %i\n", result);
exit(1);
}
fprintf(stdout, "lua ran fine\n");
lua_pop(L, lua_gettop(L));
lua_close(L);
return 0;
}
Calling that executable results however in LUA_ERRUN (2)
Error running lua: 2
I am not quite sure what I am doing wrong here, and the documentation is a little bit opaque to me -- according to the 5.2 reference manual I am using pcall correctly (function with zero args and zero return vals), and I apparently grabbed the function from the stack correctly (otherwise they earlier error would have shown).
Any idea what I am doing wrong?
luaL_dofileinstead ofluaL_loadfile. which only loads but does not run a script.if (lua_isfunction(L, -1))load(playLuaStr)(); hello();, so probably yourlua_getglobalisn't working ashellodoesn't exist.fprintf(sterr, "Error running lua: %i\n", result);- this example does not compile (sterr). Please ensure that you are copying your Minimal, Reproducible Example precisely - avoid transcribing by hand, when possible, and instead copy and paste complete examples immediately after checking their validity. It may seem minor, but typos like this can create doubt as to the correctness of other sections of the code!