Lua 'advanced' example
This commit is contained in:
parent
dc68d2bfa7
commit
0549f55bfa
3 changed files with 91 additions and 0 deletions
15
lua_advanced/Makefile
Normal file
15
lua_advanced/Makefile
Normal file
|
@ -0,0 +1,15 @@
|
|||
CC = gcc
|
||||
CFLAGS = -Wall -O2
|
||||
|
||||
TARGET = main.elf
|
||||
SRC = main.c
|
||||
|
||||
LDFLAGS += -lm
|
||||
LDFLAGS += -llua
|
||||
|
||||
$(TARGET): $(SRC)
|
||||
@echo CC $@
|
||||
@$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(TARGET)
|
63
lua_advanced/main.c
Normal file
63
lua_advanced/main.c
Normal file
|
@ -0,0 +1,63 @@
|
|||
#include <lauxlib.h>
|
||||
#include <lua.h>
|
||||
#include <lualib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
float x, y, z;
|
||||
} Vec3;
|
||||
|
||||
Vec3 table_to_vec3(lua_State *L, int index) {
|
||||
Vec3 v;
|
||||
luaL_checktype(L, index, LUA_TTABLE);
|
||||
|
||||
lua_getfield(L, index, "x");
|
||||
v.x = luaL_checknumber(L, -1);
|
||||
lua_pop(L, 1);
|
||||
|
||||
lua_getfield(L, index, "y");
|
||||
v.y = luaL_checknumber(L, -1);
|
||||
lua_pop(L, 1);
|
||||
|
||||
lua_getfield(L, index, "z");
|
||||
v.z = luaL_checknumber(L, -1);
|
||||
lua_pop(L, 1);
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
int printvec(lua_State *L) {
|
||||
Vec3 v = table_to_vec3(L, 1);
|
||||
// lua_pushnumber(L, a + b);
|
||||
printf("{ X: %.1f, Y: %.1f, Z: %.1f }\n", v.x, v.y, v.z);
|
||||
return 0; // no return values
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
// Vec3 pos = {1.0, 2.0, 3.0};
|
||||
|
||||
// printf("{ X: %.1f, Y: %.1f, Z: %.1f }\n", pos.x, pos.y, pos.z);
|
||||
|
||||
lua_State *L = luaL_newstate();
|
||||
|
||||
luaL_openlibs(L); // Load Lua standard libraries
|
||||
// luaL_requiref(L, "_G", luaopen_base, 1);
|
||||
|
||||
// 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, "printvec", printvec);
|
||||
|
||||
// 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;
|
||||
}
|
13
lua_advanced/script.lua
Normal file
13
lua_advanced/script.lua
Normal file
|
@ -0,0 +1,13 @@
|
|||
---@meta
|
||||
|
||||
---@class Vec3
|
||||
---@field x number
|
||||
---@field y number
|
||||
---@field z number
|
||||
|
||||
---Prints a vector
|
||||
---@param v Vec3
|
||||
function printvec(v) end
|
||||
|
||||
vec = { x = 1.0, y = 2.0, z = 3.0 }
|
||||
printvec(vec)
|
Loading…
Add table
Reference in a new issue