1
/* embed.c a simple test for an embeded interpreter
3
The idea is that we wrapper a few simple function (example.c)
4
and write our own app to call it.
6
What it will do is load the wrappered lib, load runme.lua and then call some functions.
7
To make life easier, all the printf's have either [C] or [Lua] at the start
8
so you can see where they are coming from.
10
We will be using the luaL_dostring()/lua_dostring() function to call into lua
21
/* the SWIG wrappered library */
22
extern int luaopen_example(lua_State*L);
24
/* a really simple way of calling lua from C
25
just give it a lua state & a string to execute
26
Unfortunately lua keeps changing its API's.
27
In lua 5.0.X its lua_dostring()
28
In lua 5.1.X its luaL_dostring()
29
so we have a few extra compiles
31
int dostring(lua_State *L, char* str) {
33
#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501))
35
ok=luaL_dostring(L,str); /* looks like this is lua 5.1.X or later, good */
38
ok=lua_dostring(L,str); /* might be lua 5.0.x, using lua_dostring */
42
printf("[C] ERROR in dostring: %s\n",lua_tostring(L,-1));
47
int main(int argc,char* argv[]) {
50
printf("[C] Welcome to the simple embedded lua example\n");
51
printf("[C] We are in C\n");
52
printf("[C] opening a lua state & loading the libraries\n");
57
printf("[C] now loading the SWIG wrappered library\n");
59
printf("[C] all looks ok\n");
61
printf("[C] lets load the file 'runme.lua'\n");
62
printf("[C] any lua code in this file will be executed\n");
63
if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) {
64
printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
67
printf("[C] We are now back in C, all looks ok\n");
69
printf("[C] lets call the function 'do_tests()'\n");
70
ok=dostring(L,"do_tests()");
71
printf("[C] We are back in C, the dostring() function returned %d\n",ok);
73
printf("[C] Lets call lua again, but create an error\n");
74
ok=dostring(L,"no_such_function()");
75
printf("[C] We are back in C, the dostring() function returned %d\n",ok);
76
printf("[C] it should also have returned 1 and printed an error message\n");
78
printf("[C] Lets call lua again, calling the greeting function\n");
79
ok=dostring(L,"call_greeting()");
80
printf("[C] This was C=>Lua=>C (getting a bit complex)\n");
82
printf("[C] all finished, closing the lua state\n");