<--!版权所有foruok,转载注明出处!-->
一个完整的例子
试验了一个完整的例子。 在C++中生成一个类,注册到lua。 从lua调用C++类的成员函数。 在Alternate.lua中写了阶乘函数factorial。 从C++中调用factorial。 Alternate.lua如下:
print(
"
nowinalternate.lua
"
);
print(
"
initialnumberofAxhSystem:
"
..AxhSystem:GetNumber());
AxhSystem:SetNumber(
15
);
print(
"
Changethenumberfromlua,new:
"
..AxhSystem:GetNumber());
print(
"
NowSetmessageto'Helloworld'
"
);
AxhSystem:SetMessage(
"
Helloworld
"
);
print(
"
AxhSystem:GetMessagereturn:
"
..AxhSystem:GetMessage());
print(
"
now,enteranumbertochangeAxhSystem'snumber:
"
);
num
=
io.read(
"
*number
"
);
print(
"
youenter:
"
..num);
print(
"
settoAxhSystem
"
)
AxhSystem:SetNumber(num);
print(
"
AxhSystem'snewnumber=
"
..AxhSystem:GetNumber());
functionfactorial(n)
if
(n
==
0
)then
return
1
;
else
return
n
*
factorial(n
-
1
);
end
end
class
CAxhSystem
{
public
:
CAxhSystem():m_nNumber(
0
)
{
memset(m_szMsg,
0
,
sizeof
(m_szMsg));
}
~
CAxhSystem()
{
}
void
SetNumber(
int
num)
{
m_nNumber
=
num;
}
int
GetNumber()
{
return
m_nNumber;
}
void
SetMessage(
const
char
*
szMsg)
{
if
(szMsg)
_tcsncpy(m_szMsg,szMsg,
256
);
}
char
*
GetMessage()
{
return
m_szMsg;
}
protected
:
int
m_nNumber;
char
m_szMsg[
256
];
}
;
CAxhSystemg_system;
LuaStateOwnerg_state;
LuaObjectg_globalObj;
int
InitLua()
{
g_state
->
OpenLibs();
g_globalObj
=
g_state
->
GetGlobals();
return
0
;
}
int
RegisterObject()
{
LuaObjectaxhmetaobj
=
g_globalObj.CreateTable(
"
AxhMetaTable
"
);
axhmetaobj.SetObject(
"
__index
"
,axhmetaobj);
//
registerfunctor
axhmetaobj.RegisterObjectDirect(
"
SetNumber
"
,(
const
CAxhSystem
*
)
0
,CAxhSystem::SetNumber);
axhmetaobj.RegisterObjectDirect(
"
GetNumber
"
,(
const
CAxhSystem
*
)
0
,CAxhSystem::GetNumber);
axhmetaobj.RegisterObjectDirect(
"
SetMessage
"
,(
const
CAxhSystem
*
)
0
,CAxhSystem::SetMessage);
axhmetaobj.RegisterObjectDirect(
"
GetMessage
"
,(
const
CAxhSystem
*
)
0
,CAxhSystem::GetMessage);
//
getluaobject
LuaObjectluasys
=
g_state
->
BoxPointer(
&
g_system);
luasys.SetMetaTable(axhmetaobj);
g_globalObj.SetObject(
"
AxhSystem
"
,luasys);
return
0
;
}
int
_tmain(
int
argc,_TCHAR
*
argv[])
{
InitLua();
RegisterObject();
g_state
->
DoFile(
"
Alternate.lua
"
);
LuaFunction
<
int
>
factorial
=
g_state
->
GetGlobal(
"
factorial
"
);
printf(
"
Nowcall'factoral'inAlternate.lua,enteranumber:
"
);
int
number;
scanf(
"
%d
"
,
&
number);
printf(
"
Youennter%d,it'sfactorial=%d
"
,number,factorial(number));
return
0
;
}