Lua embedding example
This commit is contained in:
parent
1827291dc4
commit
726f01dadf
4 changed files with 57 additions and 0 deletions
1
lua_embed/.gitignore
vendored
Normal file
1
lua_embed/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
main
|
15
lua_embed/Makefile
Normal file
15
lua_embed/Makefile
Normal file
|
@ -0,0 +1,15 @@
|
|||
CC = gcc
|
||||
CFLAGS = -Wall -O2
|
||||
|
||||
TARGET = main
|
||||
SRC = main.c
|
||||
|
||||
LDFLAGS += -lm
|
||||
LDFLAGS += -llua
|
||||
|
||||
$(TARGET): $(SRC)
|
||||
@echo CC $@
|
||||
@$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(TARGET)
|
33
lua_embed/main.c
Normal file
33
lua_embed/main.c
Normal file
|
@ -0,0 +1,33 @@
|
|||
#include <lauxlib.h>
|
||||
#include <lua.h>
|
||||
#include <lualib.h>
|
||||
|
||||
// A simple C function to add two numbers
|
||||
int c_add(lua_State *L) {
|
||||
double a = luaL_checknumber(L, 1);
|
||||
double b = luaL_checknumber(L, 2);
|
||||
lua_pushnumber(L, a + b);
|
||||
return 1; // one return value
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
lua_State *L = luaL_newstate();
|
||||
luaL_openlibs(L); // Load Lua standard libraries
|
||||
|
||||
const lua_Number ver = lua_version(NULL);
|
||||
|
||||
printf("Lua version: %.2f\n", ver);
|
||||
printf("Lua version: %s\n", LUA_VERSION);
|
||||
|
||||
// Register the C function as a global Lua function
|
||||
lua_register(L, "c_add", c_add);
|
||||
|
||||
// Run the Lua script
|
||||
if (luaL_dofile(L, "script.lua") != LUA_OK) {
|
||||
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
|
||||
lua_pop(L, 1); // remove error message
|
||||
}
|
||||
|
||||
lua_close(L);
|
||||
return 0;
|
||||
}
|
8
lua_embed/script.lua
Normal file
8
lua_embed/script.lua
Normal file
|
@ -0,0 +1,8 @@
|
|||
local result = c_add(10, 25)
|
||||
print("Result from C function: " .. result)
|
||||
|
||||
HereYouCan = {
|
||||
"Execute Arbitrary Lua Code"
|
||||
}
|
||||
|
||||
print(HereYouCan[1])
|
Loading…
Add table
Reference in a new issue