Wednesday, July 25, 2012

Calling Lua From C

One of the most interesting features of Lua is that it was designed to be easily embedded into other languages. Here's an example of how to call Lua using the C API:
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int main(int argc, char **argv)
{
    /* create a new Lua state and 
       load the standard libraries */
    lua_State *lua_state = lua_open();
    luaL_openlibs(lua_state);

    /* push the function onto the stack*/
    lua_getglobal(lua_state, "print");

    /* push the arguments */
    lua_pushstring(lua_state, "Hello World!");

    /* call the print function*/
    lua_call(lua_state, 1, 0); /* nargs, nresults */

    /* close the Lua state */
    lua_close(lua_state);
    return 0;
}
Compile with
$ gcc main.c -llua5.1 -o luatest

No comments:

Post a Comment