lua代码如下:
local dog = Dog.New()
dog:eat();
下面是C代码:
#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#define MAX_PATH 260
class dog
{
public:
dog()
{
printf("constroctor\n");
memset(sName,0,MAX_PATH);
strcpy(sName,"Kaer");
}
void init()
{
printf("init\n");
memset(sName,0,MAX_PATH);
strcpy(sName,"Kaer");
}
void eat()
{
printf("%s eat\n",sName);
}
static int eat_api(lua_State *L)
{
dog *pDog = (dog*)lua_touserdata(L,-1);
pDog->eat();
return 0;
}
static int NewDog(lua_State * L)
{
void *pMemory = lua_newuserdata(L,sizeof(dog));
// new(pMemory)dog;
//上面申请内存不会调用构造函数,因此我们这里给他调用初始化函数
dog *pDog = (dog*)pMemory;
pDog->init();
luaL_getmetatable(L,"Dog_Metetable");
lua_setmetatable(L,-2); //设置userdata的元表为Dog_Metetable,设置后,会将Dog_Metetable
出栈
return 1; //这里将栈顶的userdata返回
}
static int Export(lua_State * L)
{
luaL_Reg api_c[] = {
{"New",NewDog},
{NULL,NULL}
};
luaL_register(L,"Dog",api_c);
//设置元表
luaL_newmetatable(L,"Dog_Metetable");
//将申请的在栈顶的metatable复制一份放在栈顶
/*
void lua_pushvalue (lua_State *L, int index);
Pushes a copy of the element at the given valid index onto the stack
*/
lua_pushvalue(L,-1);
//将值设置到table中,并将上面的value出栈
lua_setfield(L,-2,"__index");
luaL_Reg api_m[] = {
{"eat", eat_api},
{NULL,NULL}
};
luaL_register(L,NULL,api_m);
// luaL_openlib(L,NULL,api_m,0);
return 0;
}
public:
char sName[MAX_PATH];
};
int _tmain(int argc, _TCHAR* argv[])
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
//注册导出类
lua_pushcfunction(L,dog::Export);
lua_pcall(L,0,0,0);
if(0 != luaL_dofile(L,"helloworld.lua"))
{
printf("%s",lua_tostring(L,-1));
}
system("pause");
return 0;
}