刚开始使用luabind,对一些基本的使用有些了解,记录下来以备查阅。这篇文章里主要讨论如何在C++中访问lua脚本中的变量,函数。
假设有一个test.lua脚本,内容如下:
1
--test.lua
2
3
function printColor()
4
colour = ColourValue(1, 1, 1, 1);
5
colour:printColor();
6
end
7
8
Config =
9

{
10
color = ColourValue(1, 1, 1, 1),
11
count = 5,
12
fun = printColor
13
14
}
ColourValue是C++类,定义如下:
1
class ColourValue
2

{
3
public:
4
ColourValue(float r = 1.0,
5
float g = 1.0,
6
float b = 1.0,
7
float a = 1.0) : mR(r), mB(b), mG(g), mA(a)
8
{
9
}
10
11
void printColor()
12
{
13
cout << mR << ", "
14
<< mG << ", "
15
<< mB << ", "
16
<< mA << ", "
17
<< endl;
18
}
19
20
protected:
21
float mR;
22
float mG;
23
float mB;
24
float mA;
25
};
C++导出类到lua中可以见之前的一篇文章(点这里),就不再赘述,假设ColourValue和它的成员函数printColor()已经导出到lua,那么如何在C++中访问Config表中的变量呢?这里就要用到luabind中的globals(lua_State* L)函数 。
这个函数返回的是全局表,表中包含加载的lua脚本中所有的变量,下面依次讲解如何来获取Config表中的三个变量。
1
// 取得全局表对象。
2
luabind::object global = luabind::globals(L);
lua脚本中的所有元素都是放在这个全局表中的,所以可以用lua table的语法来访问其中的元素:
1
// 获取脚本中的Config表。
2
luabind::object configTable = global["Config"];
这样,就可以通过configTable访问Config表中的元素了: ①访问color:
1
// 访问Config表中的color。
2
ColourValue color = luabind::object_cast<ColourValue>(configTable["color"]);
注意,这里有一个转型动作,因为ColorValue类已经导入到lua中,所以luabind知道如何转换,否则,转换将发生异常。
②访问count:
1
// 访问Config表中count。
2
int count = luabind::object_cast<int>(configTable["count"]);
有了之前的讲述,这个应该很好理解了。 ③访问printColor:
1
// 访问Config表中的printColor函数。
2
luabind::object printColor = configTable["fun"];
在C++代码中调用printColor有两种方法:
1
printColor(); // 第一种调用方法。
2
luabind::call_function<void>(printColor); // 第二种调用方法。
注意第二种调用方法使用了call_function函数的重载形式。
如果要访问全局表中的变量,方法是一样的,只不过是使用globle句柄进行访问,这里就不再赘言。