Lua embedding example
This commit is contained in:
parent
1827291dc4
commit
726f01dadf
4 changed files with 57 additions and 0 deletions
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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue