tolua++能够将c++中的对象导出到lua中,并在lua中赋值,但对于字符串,却存在支持上的问题,如:
// tolua_begin
#define MAX_LEN 10
struct SExample
{
int Num;
char cStr[MAX_LEN]; // 角色名
SExample(void)
{
memset(this, 0, sizeof(*this));
}
};
// tolua_end
对于该结构,在lua中使用
local tData = SExample:new()
tData .Num= 10 --这句正常
tData.cStr = "test" --这句将导致lua报错,reason:invalid type in variable assignment. value is 'string'; 'table' expected.
虽然可以通过其他方式来把字符串传递到C++中,但是一个结构中的字符串却需要特别处理总让人感觉别扭,经过测试,发现通过函数接口的方式可以比较优雅的解决这个问题。
// tolua_begin
#define MAX_LEN 10
struct SExample
{
int Num;
char cStr[MAX_LEN]; // 角色名
void SetcStr(char* val){memcpy(cStr,val,MAX_LEN );} //新增设置字符串的接口函数
SExample(void)
{
memset(this, 0, sizeof(*this));
}
};
// tolua_end
然后在lua中使用
local tData = SExample:new()
tData .Num= 10 --这句正常
--tData.cStr = "test" --这句将导致lua报错,reason:invalid type in variable assignment. value is 'string'; 'table' expected.
tData:SetcStr("test") --字符串能正常赋值为结构中的对应字段
或者直接将 char cStr[MAX_LEN]; // 角色名 定义改为 string strStr也可以!