CPlay/lua_advanced/esc.c
2025-12-26 03:16:28 +01:00

70 lines
1.6 KiB
C

#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdbool.h>
struct EscConfig {
int maxspeed;
float odometer;
bool started;
};
static struct EscConfig esc_config = {
.maxspeed = 100,
.odometer = 12.5f,
.started = false,
};
/* Lua: get_esc_config() -> table */
static int l_get_esc_config(lua_State *L) {
lua_newtable(L);
lua_pushstring(L, "maxspeed");
lua_pushinteger(L, esc_config.maxspeed);
lua_settable(L, -3);
lua_pushstring(L, "odometer");
lua_pushnumber(L, esc_config.odometer);
lua_settable(L, -3);
lua_pushstring(L, "started");
lua_pushboolean(L, esc_config.started);
lua_settable(L, -3);
return 1; // return the table
}
/* Lua: set_maxspeed(value) */
static int l_set_maxspeed(lua_State *L) {
int maxspeed = luaL_checkinteger(L, 1);
esc_config.maxspeed = maxspeed;
return 0;
}
/* Lua: set_started(value) */
static int l_set_started(lua_State *L) {
int started = lua_toboolean(L, 1);
esc_config.started = started;
return 0;
}
/* Lua: add_odometer(delta) */
static int l_add_odometer(lua_State *L) {
float delta = luaL_checknumber(L, 1);
esc_config.odometer += delta;
return 0;
}
static const struct luaL_Reg esc_funcs[] = {
{"get_esc_config", l_get_esc_config},
{"set_maxspeed", l_set_maxspeed},
{"set_started", l_set_started},
{"add_odometer", l_add_odometer},
{NULL, NULL},
};
/* Register the functions into Lua as global "esc" */
void register_esc(lua_State *L) {
luaL_newlib(L, esc_funcs); // create table with all funcs
lua_setglobal(L, "esc"); // set global "esc"
}