Skip to content

Instantly share code, notes, and snippets.

@jgibbard
Created December 5, 2024 07:38
Show Gist options
  • Save jgibbard/4873c17215ebccf9a0e33b9d7c7b8e9a to your computer and use it in GitHub Desktop.
Save jgibbard/4873c17215ebccf9a0e33b9d7c7b8e9a to your computer and use it in GitHub Desktop.
Lua Example
#include <iostream>
#include <vector>
#ifdef __cplusplus
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#endif
static uint8_t* g_packet_ptr;
static uint32_t g_packet_size;
int getByte(lua_State *L) {
unsigned int index = luaL_checkinteger(L, 1);
if (index < g_packet_size) {
lua_pushinteger(L, g_packet_ptr[index]);
} else {
lua_pushnil(L);
}
return 1; // Number of return values
}
int packetSize(lua_State *L) {
lua_pushinteger(L, g_packet_size);
return 1;
}
int main() {
lua_State* L = luaL_newstate(); // Create a new Lua state
luaL_openlibs(L); // Load Lua libraries
lua_register(L, "getByte", getByte);
lua_register(L, "packetSize", packetSize);
{
// My new packet
std::vector<uint8_t> packet_data = {10,45,13,1,45,201,32};
// Set globals to point to new packet - don't copy the data
g_packet_ptr = packet_data.data();
g_packet_size = packet_data.size();
const char *luaScript1 = R"(
local value = getByte(3)
if value then
print("Value at index 3: " .. value)
else
print("Index out of range")
end
)";
if (luaL_dostring(L, luaScript1) != LUA_OK) {
std::cerr << "Failed to run Lua script: " << lua_tostring(L, -1) << std::endl;
}
const char *luaScript2 = R"(if packetSize() > 5 and getByte(0) == 10 and getByte(4) == 45 then print("Match") end)";
if (luaL_dostring(L, luaScript2) != LUA_OK) {
std::cerr << "Failed to run Lua script: " << lua_tostring(L, -1) << std::endl;
}
// Reset Globals
g_packet_ptr = nullptr;
g_packet_size = 0;
}
lua_close(L);
return 0;
}
# Compiler and flags
CXX := g++
CXXFLAGS := -Wall -std=c++11 -I./lua
# Directories
LUA_DIR := ./lua
SRC_DIR := .
# Files
SRC := $(wildcard $(SRC_DIR)/*.cpp)
OBJ := $(SRC:$(SRC_DIR)/%.cpp=$(SRC_DIR)/%.o)
LUA_SRC := $(wildcard $(LUA_DIR)/*.c)
PROG_NAME := my_app
# Build the final executable
$(PROG_NAME): $(OBJ) $(LUA_DIR)/liblua.a
$(CXX) $(CXXFLAGS) -o $(PROG_NAME) $^ -ldl -lm
# Compile any C++ source files into object files
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
# Build statically linkable lua lib
$(LUA_DIR)/liblua.a: $(LUA_SRC)
$(MAKE) -C $(LUA_DIR) a
all: $(PROG_NAME)
clean:
$(MAKE) -C $(LUA_DIR) clean
rm $(PROG_NAME) $(OBJ)
# Phony targets
.PHONY: clean all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment