- Source: Lucas Klassmann blog
Examples
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main(int argc, char ** argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// Work with lua API
lua_close(L);
return 0;
}
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main(int argc, char ** argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// Our Lua code, it simply prints a Hello, World message
char * code = "print('Hello, World')";
// Here we load the string and use lua_pcall for run the code
if (luaL_loadstring(L, code) == LUA_OK) {
if (lua_pcall(L, 0, 0, 0) == LUA_OK) {
// If it was executed successfuly we
// remove the code from the stack
lua_pop(L, lua_gettop(L));
}
}
lua_close(L);
return 0;
}
(Note that Lucas' blog contains a typo: his code has a lower case l in lua_gettop(L)
which doesn't compile.)
Makefile
all: a b
%: %.c
gcc -o $@ $< -I/usr/include/lua5.4 -llua5.4
dofile
We can already execute lua files.
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main(int argc, char ** argv) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// Work with lua API
char * code = "dofile('hello.lua')";
// Here we load the string and use lua_pcall for run the code
if (luaL_loadstring(L, code) == LUA_OK) {
if (lua_pcall(L, 0, 0, 0) == LUA_OK) {
// If it was executed successfuly we
// remove the code from the stack
lua_pop(L, lua_gettop(L));
}
}
lua_close(L);
return 0;
}
Shared Library
// exl001.c
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdlib.h>
typedef struct {
lua_State* state;
} MyLua;
MyLua* create_my_lua() {
MyLua* mylua = (MyLua*)malloc(sizeof(MyLua));
mylua->state = luaL_newstate();
luaL_openlibs(mylua->state);
return mylua;
}
void destroy_my_lua(MyLua* mylua) {
lua_close(mylua->state);
free(mylua);
}
static void test1(MyLua* mylua);
void test() {
MyLua *mylua = create_my_lua();
test1(mylua);
destroy_my_lua(mylua);
}
static void test1(MyLua* mylua) {
char * code = "dofile('hello.lua')";
lua_State* L = mylua->state;
// Here we load the string and use lua_pcall for run the code
if (luaL_loadstring(L, code) == LUA_OK) {
if (lua_pcall(L, 0, 0, 0) == LUA_OK) {
// If it was executed successfuly we
// remove the code from the stack
lua_pop(L, lua_gettop(L));
}
}
}
// hello.lua
print("Hello, World! Woohoo!")
import ctypes
lib = ctypes.cdll.LoadLibrary("./exl001.so")
test = lib.test
test()
all: exl001.so
exl001.so: exl001.c
gcc -I /usr/include/lua5.4 -o $@ $< -shared -llua5.4