forked from Veinin/lua-c-api-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
04_call_lua_func.c
40 lines (29 loc) · 876 Bytes
/
04_call_lua_func.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "errors.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if(luaL_loadfile(L, "call_lua_func.lua"))
err_exit(L, "luaL_loadfile failed.\n");
if(lua_pcall(L, 0, 0, 0))
err_exit(L, "lua_pcall failed.\n");
printf("In C, calling Lua->sayHello()\n");
lua_getglobal(L, "sayHello"); //Tell it to run test2.lua -> sayHello()
if(lua_pcall(L, 0, 0, 0))
err_exit(L, "lua_pcall failed.\n");
printf("Back in C again\n");
printf("\nIn C, calling Lua->add()\n");
lua_getglobal(L, "add"); //Tell it to run test2.lua -> add()
lua_pushnumber(L, 1);
lua_pushnumber(L, 5);
if(lua_pcall(L, 2, 1, 0))
err_exit(L, "lua_pcall failed.\n");
printf("Back in C again\n");
int returnNum = lua_tonumber(L, -1);
printf("Returned number : %d\n", returnNum);
lua_close(L);
return 0;
}