编辑:[解答2中的解决方案]
我是LUA的新手,我很难尝试做我想做的事。我有一个看起来像这样的C ++对象:
C ++对象定义
struct TLimit
{
bool enabled;
double value;
TLimit() : enabled(false), value(0.0) {}
~TLimit() {}
};
class TMeaurement
{
public:
TMeasurement() : meas(0.0) {}
~TMeasurement() {}
TLimit min;
TLimit max;
double meas;
};
我希望能够在LUA中以下列形式访问TMeasurement类型的对象:
LUA希望使用
-- objmeas is an instance of TMeasurement
objmeas.min.enabled = true
print(objmeas.min.value);
...等
另一件事,我不希望LUA为TMeasurement类型的对象实例分配内存。这将在我的C ++代码中完成。我尝试过很多不同的东西,都不成功。我现在将发布我的最后一次尝试。
在我的C ++代码中,我定义了以下内容:
TLimit - 获取将映射到__index
的函数#define LUA_MEAS_LIMIT "itse.measurement.limit"
extern int llim_get(lua_State* L)
{
TLimit* lim = (TLimit*)lua_chekuserdata(L, 1, LUA_MEAS_LIMIT);
std::string key = std::string(luaL_checkstring(L, 2));
//-- this is only to check what is going on
std::cout << "lim.get: " << key << std::endl;
if(key.find("enabled") == 0)
lua_pushboolean(L, lim->enabled);
else if(key.find("value") == 0)
lua_pushnumber(L, lim->value);
else
return 0; //-- should return some sort of error, but let me get this working first
return 1;
}
TLimit - 设置将映射到__newindex的函数
extern int llim_set(lua_State* L)
{
TLimit* lim = (TLimit*)lua_chekuserdata(L, 1, LUA_MEAS_LIMIT);
std::string key = std::string(luaL_checkstring(L, 2));
//-- this is only to check what is going on
std::cout << "limit.set: " << key << " <-" << std::endl;
if(key.find("enabled") == 0)
lim->enabled = lua_toboolean(L, 3);
else if(key.find("value") == 0)
lim->value = lua_tonumber(L, 3);
return 0;
}
现在,TMeasurement类还有一个函数。 (我不会在这个例子中提供成员的设置功能&#34; meas&#34;)。
TMeasurement - 获取__index的功能
#define LUA_MEASUREMENT "itse.measurement"
extern int lmeas_get(lua_State* L)
{
TMeasurement* test = (TMeasurement*)lua_checkuserdata(L, 1, LUA_MEASUREMENT);
std::string key = std::string(luaL_checkstring(L, 2));
//-- this is only to check what is going on
std::cout << "meas." << key << " ->" << std::endl;
if(key.find("meas") == 0)
lua_pushinteger(L, test->meas);
else if(key.find("min") == 0)
{
lua_pushlightuserdata(L, &test->min);
luaL_getmetatable(L, LUA_MEAS_LIMIT);
lua_setmetatable(L, -2);
}
else if(key.find("max") == 0)
{
lua_pushlightuserdata(L, &test->max);
luaL_getmetatable(L, LUA_MEAS_LIMIT);
lua_setmetatable(L, -2);
}
else
return 0; //-- should notify of some error... when I make it work
return 1;
}
现在,代码中为这两个对象创建元数据的部分:
C ++ - 发布元数据
(更别关注nsLUA :: safeFunction&lt; ...&gt;位,它只是一个模板函数,它将在&lt;&gt;的安全模式下执行该函数&#34; ...它会在遇到错误时弹出MessaegBox)
static const luaL_Reg lmeas_limit_f[] = { { NULL, NULL} };
static const luaL_Reg lmeas_limit[] =
{
{ "__index", nsLUA::safeFunction<llim_get> },
{ "__newindex", nsLUA::safeFunction<lllim_set> },
{ NULL, NULL }
};
//-----------------------------------------------------------------------------
static const luaL_Reg lmeas_f[] = { { NULL, NULL} };
static const luaL_Reg lmeas[] =
{
{ "__index", nsLUA::safeFunction<lmeas_get> },
{ NULL, NULL }
};
//-----------------------------------------------------------------------------
int luaopen_meas(lua_State* L)
{
//-- Create Measurement Limit Table
luaL_newmetatable(L, LUA_MEAS_LIMIT);
luaL_setfuncs(L, lmeas_limit, 0);
luaL_newlib(L, lmeas_limit_f);
//-- Create Measurement Table
luaL_newmetatable(L, LUA_MEASUREMENT);
luaL_setfuncs(L, lmeas, 0);
luaL_newlib(L, lmeas_f);
return 1;
}
最后,我在C ++中的主要功能,初始化LUA,创建对象TMeasurement的实例,将其作为全局传递给LUA并执行lua脚本。大多数此功能都包含在另一个名为LEngine的类中:
C ++ - 主要功能
int main(int argc, char* argv[])
{
if(argc < 2)
return show_help();
nsLUA::LEngine eng;
eng.runScript(std::string(argv[1]));
return 0;
}
//-----------------------------------------------------------------------------
int LEngine::runScript(std::string scrName)
{
//-- This initialices LUA engine, openlibs, etc if not already done. It also
// registers whatever library I tell it so by calling appropriate "luaL_requiref"
luaInit();
if(m_lua) //-- m_lua is the lua_State*, member of LEngine, and initialized in luaInit()
{
LMeasurement measurement;
measurement.value = 4.5; //-- for testing purposes
lua_pushlightuserdata(m_lua, &tst);
luaL_getmetatable(m_lua, LUA_MEASUREMENT);
lua_setmetatable(m_lua, -2);
lua_setglobal(m_lua, "step");
if(luaL_loadfile(m_lua, scrName.c_str()) || lua_pcall(m_lua, 0, 0, 0))
processLuaError(); //-- Pops-up a messagebox with the error
}
return 0;
}
现在,最后问题。当我执行任何lua脚本时,我可以访问步骤没有问题,但我只能访问一个memebr&#34; min&#34;或者&#34; max&#34;第一次......任何后续访问都会出错。
LUA - 示例一
print(step.meas); -- Ok
print(step.min.enabled); -- Ok
print(step.min.enabled); -- Error: attempt to index field 'min' (a nil value)
此脚本生成的输出为:
first script line: print(step.meas);
meas.meas -> this comes from lmeas_get function
4.5 this is the actual print from lua sentence
second script line: print(step.min.enabled)
meas.min -> accessing step.min, call to function lmeas_get
limit.get: enabled -> accessing min.enabled, call to function llim_get
false actual print from script sentence
third script line: print(step.min.enabled)
limit.get: min -> accessing min from limit object, call to llim_get ???????
因此。我第一次访问该字段后#min;&#39; (或者&#39; max&#39;就此而言),任何后续尝试获取它将返回&#34;尝试访问索引......&#34;错误。我是先访问__index(本地e = step.min.enabled)函数还是__newindex函数(step.min.enabled = true)并不重要。
我第一次访问对象步骤的最小元素时似乎搞乱了LUA堆栈。它以某种方式&#34;取代&#34; &#34;指向步骤&#34;从LUA_MEASUREMENT metatable到LUA_MEAS_LIMIT ......我根本就不知道为什么。
请帮助......我这么乱的是什么?
谢谢你,对不起这篇长篇文章感到抱歉......我只是不知道如何缩短篇幅。
答案 0 :(得分:2)
首先,感谢@siffiejoe和@greatwolf的帖子。是他们向我解释我做错了什么。
现在,我的解决方案。我很确定这个解决方案并不是最好的,但它到目前为止满足了我的需求。如果有人有任何建议,请查看/查找潜在的错误,或只是蚂蚁评论,请这样做。
解决方案 - 想法
因为在LUA中,所有lightuserdata共享相同的metatable,所以我决定使我想要传递给LUA的lightuserdata指针的所有结构和类与我称为LMetaPointer
的公共类共享相同的继承。 。此类将发布metatable并将__index
和__newindex
映射到给定的静态方法LMetaPointer::__index
和LMetaPointer::__newindex
。该类还包含static std::map
(列表)指向所有LMetaPointer
实例的指针。该类的构造函数确保将新创建的实例添加到此映射中。
每当在lua中调用元方法__index
或__newindex
时,都会执行相应的LMetaPointer::__index
或LMetaPointer::__newindex
。此方法在地图中搜索负责方法调用的相应指针,并调用自己的get
或set
方法,这些方法在LMetaPointer
类中定义为纯虚拟。
我知道这可能有点令人困惑,所以我现在将发布课程LMetaPointer
的定义
解决方案 - 框架:LMetaPointer类
//-----------------------------------------------------------------------------
#define LUA_METAPOINTER "itse.metapointer" //-- Name given to the metatable for all lightuserdata (instances of LMetaPointer in C++)
//-----------------------------------------------------------------------------
class LMetaPointer
{
private:
static lua_State* m_lua; //-- All LMetaPointers will share a common lua State
static const luaL_Reg m_lmembers[]; //-- Member functions (for later expansion)
static const luaL_Reg m_lfunctions[]; //-- Metamethods
static std::map<LMetaPointer*, std::string> m_pointers; //-- List of all LMetaPointer instances
std::string m_name; //-- Name of LUA global variable pointing to me.
static int __index(lua_State* L); //-- Shall be mapped to __index metamethod of the metatable for all lightuserdata pointers
static int __newindex(lua_State* L); //-- Shall be mapped to __newindex metamethod of the metatable for all lightuserdata pointers
void initialize(lua_State* L); //-- Creates the metatable (only once) and publishes it
protected:
public:
LMetaPointer(lua_State* L);
virtual ~LMetaPointer();
inline lua_State* lua() { return m_lua; }
inline std::string global() { return m_name; }
inline size_t size() { return m_pointers.size(); }
void setGlobal(std::string n); //-- Shall make this pointer globally accessible to LUA
virtual int get(lua_State* L) = 0; //-- To be implemented by inherited classes
virtual int set(lua_State* L) = 0; //-- To be implemented by inherited classes
LMetaPointer* operator [](std::string n);
};
现在遵循类
的实现//-----------------------------------------------------------------------------
#define lua_checkmpointer(L) (LMetaPointer*)luaL_checkudata(L, 1, LUA_METAPOINTER)
//-----------------------------------------------------------------------------
lua_State* LMetaPointer::m_lua = NULL;
std::map<LMetaPointer*, std::string> LMetaPointer::m_pointers;
const luaL_Reg LMetaPointer::m_lmembers[] = { { NULL, NULL } };
const luaL_Reg LMetaPointer::m_lfunctions[] =
{
{ "__index", LMetaPointer::__index },
{ "__newindex", LMetaPointer::__newindex },
{ NULL, NULL }
};
//-----------------------------------------------------------------------------
LMetaPointer::LMetaPointer(lua_State* L) : m_name("")
{
//-- Make sure we have created the metatable
initialize(L);
//-- Add this pointer as of kind LUA_METAPOINTER metatable. This bit of code
// might not be necessary here. (To be removed)
lua_pushlightuserdata(m_lua, this);
luaL_getmetatable(m_lua, LUA_METAPOINTER);
lua_setmetatable(m_lua, -2);
//-- Add myself to the map of all metapointers
m_pointers[this] = m_name;
}
//-----------------------------------------------------------------------------
LMetaPointer::~LMetaPointer()
{
//-- Remove myself from the map of metapointers
std::map<LMetaPointer*, std::string>::iterator found = m_pointers.find(this);
if(found != m_pointers.end())
m_pointers.erase(found);
}
//-----------------------------------------------------------------------------
int LMetaPointer::__index(lua_State* L)
{
//-- Obtain the object that called us and call its get method.
// Since get and set are pure virtual, all inherited classes of LMetaPointer
// must implement it, and, upon the call from here, the correct 'get' method
// will be called.
LMetaPointer* p = lua_checkmpointer(L);
return p->get(L);
}
//-----------------------------------------------------------------------------
int LMetaPointer::__newindex(lua_State* L)
{
//-- Obtain the object that called us and call its set method
// Since get and set are pure virtual, all inherited classes of LMetaPointer
// must implement it, and, upon the call from here, the correct 'get' method
// will be called.
LMetaPointer* p = lua_checkmpointer(L);
return p->set(L);
}
//-----------------------------------------------------------------------------
void LMetaPointer::initialize(lua_State* L)
{
//-- Only create the metatable the first time and instance of LMetaPointer is created
if(!m_lua)
{
m_lua = L;
luaL_newmetatable(m_lua, LUA_METAPOINTER);
luaL_setfuncs(L, m_lfunctions, 0);
luaL_newlib(L, m_lmembers);
}
}
//-----------------------------------------------------------------------------
void LMetaPointer::setGlobal(std::string n)
{
//-- Make myself (this) a global variable in LUA with name given by 'n'
std::map<LMetaPointer*, std::string>::iterator found = m_pointers.find(this);
if(found != m_pointers.end())
{
m_name = n;
found->second = m_name;
lua_pushlightuserdata(m_lua, this);
luaL_getmetatable(m_lua, LUA_METAPOINTER);
lua_setmetatable(m_lua, -2);
lua_setglobal(m_lua, m_name.c_str());
}
}
//-----------------------------------------------------------------------------
LMetaPointer* LMetaPointer::operator [](std::string n)
{
//-- Simply for completeness, allow all metapointer access all other by their
// name. (Notice though that since names are only assigned to instances made
// global, this operator will only work properly when searching for a pointer
// made global. ALl othe rpointers have an empty name.
std::map<LMetaPointer*, std::string>::iterator iter = m_pointers.begin();
while(iter != m_pointers.end())
{
if(iter->second == n)
return iter->first;
++iter;
}
return NULL;
}
现在,这个类允许我定义任何其他结构或类,并通过混合方法或名称将LUA指针(lightuserdata)传递给它。对于我原始问题中的示例,这意味着定义以下内容:
注意:我已经扩展了一点我的示例,现在称为LMeasLimit
是之前的TLimit
,LMeasurement
是一个新类,LTest
是之前的TMeaasurement
解决方案 - 实施
//-------------------------------------------------------------------------
struct LMeasLimit : public LMetaPointer
{
bool enabled; //-- Is the limit enabled?
double value; //-- Limit value;
LMeasLimit(lua_State* L) : LMetaPointer(L), enabled(false), value(0.0) {}
~LMeasLimit() {}
int get(lua_State* L); //-- Implements LMetaPointer::get
int set(lua_State* L); //-- Implements LMetaPointer::set
};
//-------------------------------------------------------------------------
struct LMeasurement : public LMetaPointer
{
double value; //-- Measurement
LStepResult result; //-- Result of test
std::string message; //-- Message to display
LMeasurement(lua_State* L) : LMetaPointer(L), value(0.0), result(srNothing), message("") {}
~LMeasurement() {}
int get(lua_State* L); //-- Implements LMetaPointer::get
int set(lua_State* L); //-- Implements LMetaPointer::set
};
//-------------------------------------------------------------------------
struct LTest : public LMetaPointer
{
int id; //-- ID of test
std::string name; //-- Name of test
LMeasLimit max; //-- Max limit for measure
LMeasLimit min; //-- Min limit for measure
LMeasurement meas; //-- Measurement
LTest(lua_State* L) : LMetaPointer(L), id(0), name(""), min(L), max(L), meas(L) {}
~LTest() {}
int get(lua_State* L); //-- Implements LMetaPointer::get
int set(lua_State* L); //-- Implements LMetaPointer::set
};
//-----------------------------------------------------------------------------
和不同类的不同方法的定义
int LMeasLimit::get(lua_State* L)
{
std::string key = std::string(luaL_checkstring(L, 2));
if(key.find("enabled") == 0)
lua_pushboolean(L, enabled);
else if(key.find("value") == 0)
lua_pushnumber(L, value);
else
return 0;
return 1;
}
//-----------------------------------------------------------------------------
int LMeasLimit::set(lua_State* L)
{
std::string key = std::string(luaL_checkstring(L, 2));
if(key.find("enabled") == 0)
enabled = lua_toboolean(L, 3);
else if(key.find("value") == 0)
value = lua_tonumber(L, 3);
return 0;
}
//-----------------------------------------------------------------------------
int LMeasurement::get(lua_State* L)
{
std::string key = std::string(luaL_checkstring(L, 2));
if(key.find("value") == 0)
lua_pushnumber(L, value);
else if(key.find("result") == 0)
lua_pushunsigned(L, result);
else if(key.find("message") == 0)
lua_pushstring(L, message.c_str());
else
return 0;
return 1;
}
//-----------------------------------------------------------------------------
int LMeasurement::set(lua_State* L)
{
std::string key = std::string(luaL_checkstring(L, 2));
if(key.find("value") == 0)
value = lua_tonumber(L, 3);
else if(key.find("result") == 0)
result = LStepResult(lua_tounsigned(L, 3));
else if(key.find("message") == 0)
message = std::string(lua_tostring(L, 3));
return 0;
}
//-----------------------------------------------------------------------------
int LTest::get(lua_State* L)
{
std::string key = std::string(luaL_checkstring(L, 2));
if(key.find("id") == 0)
lua_pushinteger(L, id);
else if(key.find("name") == 0)
lua_pushstring(L, name.c_str());
else if(key.find("min") == 0)
{
lua_pushlightuserdata(L, &min);
luaL_getmetatable(L, LUA_METAPOINTER);
lua_setmetatable(L, -2);
}
else if(key.find("max") == 0)
{
lua_pushlightuserdata(L, &max);
luaL_getmetatable(L, LUA_METAPOINTER);
lua_setmetatable(L, -2);
}
else if(key.find("meas") == 0)
{
lua_pushlightuserdata(L, &meas);
luaL_getmetatable(L, LUA_METAPOINTER);
lua_setmetatable(L, -2);
}
else
return 0;
return 1;
}
//-----------------------------------------------------------------------------
int LTest::set(lua_State* L)
{
std::string key = std::string(luaL_checkstring(L, 2));
if(key.find("id") == 0)
id = lua_tointeger(L, 3);
else if(key.find("name") == 0)
name = std::string(lua_tostring(L, 3));
return 0;
}
解决方案 - 全部放在一起
最后的修改是在我们原始问题的LEngine::runScript
中。
int LEngine::runScript(std::string scrName)
{
luaInit();
if(m_lua)
{
LTest tst(m_lua);
tst.name = std::string("mierda_esta");
tst.setGlobal("step");
if(luaL_loadfile(m_lua, scrName.c_str()) || lua_pcall(m_lua, 0, 0, 0))
processLuaError();
}
return 0;
}
最后,我将展示一个用于测试及其输出的LUA脚本。
测试 - LUA脚本
print("step.id = " .. step.id)
print("step.name = " .. step.name)
print(step.min.enabled)
print("step.min.value = " .. step.min.value)
step.id = 1
step.name = "nombre del test";
step.min.enabled = true;
step.min.value = 5.6;
print("step.id = " .. step.id)
print("step.name = " .. step.name)
print(step.min.enabled)
print("step.min.value = " .. step.min.value)
测试 - 输出
step.id = 0
step.name = mierda_esta
false
step.min.value = 0
step.id = 1
step.name = nombre del test
true
step.min.value = 5.6
所以,这一切现在似乎都在我想要它。我仍然需要修改这个LMetaPointer
,以便能够以类似于C ++的方式调用任何继承类的成员函数。但这应该是另一个故事。
再次感谢@siffiejoe和@greatwolf的时间和回复。
答案 1 :(得分:1)
正如评论中已经提到的,所有lightuserdata共享一个metatable(请参阅here),因此所有lightuserdata值始终处理完全相同。如果更改了一个lightuserdata的metatable,那么它将针对所有这些更改。这就是你的代码中发生的事情:
LEngine::runScript
中,您使所有lightuserdata都像TMeasurement
个对象一样。这对于全局变量step
中的值是可以的。step.min
时,您使所有lightuserdata的行为与TLimit
个对象相同(在lmeas_get
中)。这适用于step.min
推送的值,但现在step
中的值也表现得像TLimit
,所以step.min
时,step
充当TLimit
对象,因此它没有字段min
并返回{{ 1}}。Lightuserdata根本不适合这项工作。参见例如this discussion适用于可以使用lightuserdata的情况。对于其他一切,您需要完整的用户数据。与lightuserdata相比,这将分配一些额外的内存(对不起,无法帮助),但你可以做一些缓存,以避免产生太多临时数据。
因此,对于nil
值,您使用一个完整的用户数据,其中包含指向step
对象的指针。您还将新表设置为uservalue(请参阅lua_setuservalue
),该表将充当子用户数据的缓存。使用TMeasurement
参数调用lmeas_get
时,使用相同的键查看uservalue表。如果没有为此字段找到预先存在的用户数据,则创建一个新的完整用户数据,其中包含指向"min"/"max"
子对象的指针(使用适当的元表),将其放入缓存中,然后将其返回。如果您的对象生命周期将来变得更加复杂,您应该将TLimit
子用户数据的后向引用添加到父TLimit
用户数据,以确保在所有引用之前不会对后者进行垃圾回收前者也消失了。您也可以使用uservalue表。