您的位置:首页 > 编程语言 > Lua

lua调用c++

2017-08-01 19:20 162 查看
TestLib.h

//
// TestLib.h
// TestLua
//
// Created by jianan on 2017/8/1.
//
//

#ifndef TestLib_h
#define TestLib_h

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

// 全局的函数,用于导出,内部完成注册和初始化功能
int luaopen_testLib(lua_State *L);

#endif /* TestLib_h */TestLib.cpp
//
// TestLib.cpp
// TestLua
//
// Created by jianan on 2017/8/1.
//
//

#include <stdio.h>
#include "TestLib.h"

static int testFunc(lua_State *L)
{
printf("http://www.jellthink.com\n");
lua_pushnumber(L, 250);
lua_pushstring(L, "hello lua");
return 2; //表示2个参数
}

static const struct luaL_Reg myLib[] =
{
{"test", testFunc},
{NULL, NULL}
};

int luaopen_testLib(lua_State *L)
{
luaL_register(L, "testLib", myLib);
return 1; // 把表压入了栈中,所以就需要返回1
}

AppDelegate.cpp
#include "TestLib.h"
bool AppDelegate::applicationDidFinishLaunching()
{

lua_State* L = engine->getLuaStack()->getLuaState();
lua_module_register(L);

luaopen_testLib(L);
}


config.lua
require "testLib"
local a, b = testLib.test()
print(a..b)

--http://www.jellthink.com
--250hello lua
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: