diff options
author | Richard Maw <richard.maw@gmail.com> | 2013-04-10 21:48:06 +0100 |
---|---|---|
committer | Richard Maw <richard.maw@gmail.com> | 2013-04-11 22:16:31 +0100 |
commit | 54b771278d62cf580e02665b4c7448bad0e23fac (patch) | |
tree | 0e87963722bff2128f383de9a86f0a3f2b7ebc6c | |
parent | c660c085ad26a8d215f8648fe96fc80c8086ab6f (diff) | |
download | binding-lua-from-c-master.tar.bz2 |
hello: execute hello.lua to get the output stringHEADscripted-hellomaster
-rw-r--r-- | hello.c | 49 | ||||
-rw-r--r-- | hello.lua | 1 |
2 files changed, 49 insertions, 1 deletions
@@ -1,6 +1,53 @@ #include <stdio.h> +/* lua.h provides core functions, these include everything starting lua_ */ +#include <lua.h> +/* lauxlib.h provides convenience functions, these start luaL_ */ +#include <lauxlib.h> + int main(void){ - printf("Hello World!\n"); + /* The lua_State structure encapsulates your lua runtime environment + luaL_newstate allocates and initializes it. + There also exists a lua_newstate, which takes parameters for a custom + memory allocator, since the lua runtime needs to allocate memory. + luaL_newstate is a wrapper, which uses the standard C library's realloc, + and aborts on allocation failure. + */ + lua_State *L = luaL_newstate(); + if (!L) { + perror("Creating lua state"); + return 1; + } + + /* The following executes the file hello.lua, which returns the string + intended to be printed. + Likewise it is an auxiliary function, which reads a file, + compiles the contents into a function, then calls it. + */ + if (luaL_dofile(L, "hello.lua")) { + /* dofile returns a string on the lua stack in the case of error + which says what went wrong, a pointer to it is retrieved with + lua_tostring, this exists inside the lua_State structure, so + if you need it after the next call to lua you have to copy it + */ + char const *errmsg = lua_tostring(L, 1); + fprintf(stderr, "Failed to execute hello.lua: %s\n", errmsg); + return 2; + } + + /* A file can take parameters and return values like a function. + The result is passed to printf, so IO is done outside of lua. + */ + char const *result = lua_tostring(L, 1); + if (!result) { + fprintf(stderr, "hello.lua did not return a string\n"); + return 3; + } + printf("%s\n", result); + + /* lua_close frees up any resources used by the lua runtime + This is not necessary here, since the program is about to exit. + */ + lua_close(L); return 0; } diff --git a/hello.lua b/hello.lua new file mode 100644 index 0000000..cfcbc24 --- /dev/null +++ b/hello.lua @@ -0,0 +1 @@ +return "Hello World!" |