目标: 用c++读取下面lua文件的变量,表,调用函数:
由于还有些表要我配,今天任务延期,没完成,明日再更新
name = "织法" age = 25 color = {r=1.0,g=0.2,b=0.5,a=1.0} arr = {1,2,3,4,5} function Add(a,b) return a+b end function Squar(num) return num * num end function Dist2D(pointA,pointB) local xdst = pointA.x - pointB.x local ydst = pointA.y - pointB.y return math.sqrt(Squar(xdst) + Squar(ydst)) end print("hello lua")
c++ luabase.h
#pragma once #include<string> #include<cstring> #include<cstdlib> #include<cstdio> using namespace std; #include "lua.hpp" extern lua_State *L; struct luaColor { double r, g, b, a; void output(); }; bool lua_checkf(int err); #define LUA_CHECK(f) do{if(!lua_checkf(f)) return false;}while(0) void loadLua(); void cloaseLua(); int loadInteger(const char* v_key); const char* loadString(const char* v_key); int lua_add(int a, int b); bool loadColor(luaColor *v_color);
c++ luabase.cpp
#include"luabase.h" lua_State *L; bool lua_checkf(int err) { if (!err) { printf("报错啦,错误信息是%s\n", lua_tostring(L, -1)); return false; } return true; } #define LUA_CHECK(f) do{if(!lua_checkf(f)) return false;}while(0) void loadLua() { const string filename = "lua/test.lua"; L = luaL_newstate(); luaopen_base(L); luaL_openlibs(L); luaL_dofile(L, filename.data()); } void cloaseLua() { lua_close(L); } int loadInteger(const char* v_key) { LUA_CHECK(lua_getglobal(L, v_key)); int rst = lua_tointeger(L, -1); lua_pop(L, 1); return rst; } const char* loadString(const char* v_key) { LUA_CHECK(lua_getglobal(L, v_key)); lua_pop(L, 1); return lua_tostring(L, -1); } int lua_add(int a,int b) { lua_getglobal(L, "Add"); lua_pushinteger(L, a); lua_pushinteger(L, b); if (lua_pcall(L, 2, 1, 0) != LUA_OK) { printf("报错啦,错误信息是%s\n",lua_tostring(L, -1)); } int rst = lua_tointeger(L, -1); lua_pop(L, 3); return rst; } static double getDoubleField() { } bool loadColor(luaColor *v_color) { LUA_CHECK(lua_getglobal(L, "color")); LUA_CHECK(lua_getfield(L, -1, "r")); v_color->r = lua_tonumber(L, -1); lua_pop(L, 1); LUA_CHECK(lua_getfield(L, -1, "g")); v_color->g = lua_tonumber(L, -1); lua_pop(L, 1); LUA_CHECK(lua_getfield(L, -1, "b")); v_color->b = lua_tonumber(L, -1); lua_pop(L, 1); LUA_CHECK(lua_getfield(L, -1, "a")); v_color->a = lua_tonumber(L, -1); lua_pop(L, 1); lua_pop(L, 1); return true; } void luaColor::output() { printf("color:{%d,%d,%d,%d}", (int)(r*255), (int)(g*255), (int)(b*255), (int)(a*255)); }
时间: 2024-10-23 00:16:59