该程序主要是C++与Lua之间的相互调用示例。
执行内容:
(1)新建一个lua_State
(2)打开常用库,如io,os,table,string等
(3)注册C函数
(4)导入程序所在目录下所有*.lua文件
(5)调用Lua中的MainEntry()函数

我们可能在lua_functions.cpp文件中加入我们新增的C函数,将C++与Lua结合为一个更强大的程序。

下载到本地之后,将Makefile.txt改成Makefile,然后make就可以了。

存在的问题:好像在main()调用MainEntry()时,传入的argv在MainEntry(...)中的arg中没有。
​1. [文件] main.cpp ~ 
#include <iostream>
#include <vector>
 
#include <lua.hpp>
#include "type.h"
#include "util.h"
 
using namespace std;
 
extern lua_register_t lua_cfunction_list[];
 
void open_all_libs(lua_State *L)
{
    luaopen_base(L);
    luaopen_io(L);
    luaopen_os(L);
    luaopen_string(L);
    luaopen_table(L);
    luaopen_math(L);
    luaopen_bit32(L);
}
 
void register_functions(lua_State *L)
{
    lua_register_t *p = lua_cfunction_list;
    while (p->name) {
        lua_pushcfunction(L, p->pfunc);
        lua_setglobal(L, p->name);
        ++p; 
    }
}
 
bool load_lua_files(lua_State *L, const char *dir_path)
{
    vector<string> file_list;
    find_files("./", ".lua", file_list);
    vector<string>::iterator iter = file_list.begin();
    for (; iter != file_list.end(); ++iter) {
        if (luaL_dofile(L, iter->c_str())) {
            cout << "ERR: loadfile " << *iter << " fail: " << lua_tostring(L, -1) << endl;
            return false;
        }
    }
    return true;
}
 
int main (int argc, char **argv)
{
    lua_State *L = luaL_newstate();
    if (L == NULL) {
        cout << "ERR: new state fail!" << endl;
        return 0;
    }
 
    /// open all lua library, such as: io,os,string,table,math...
    open_all_libs(L);           
 
    /// register C functions to lua
    register_functions(L);      
 
    /// load lua file in ./ directory.
    load_lua_files(L, "./");    
 
    /// run lua function "MainEntry()"
    lua_getglobal(L, "MainEntry");
    if (lua_type(L, -1) == LUA_TFUNCTION) {
        for (int i = 0; i < argc; ++i) {
            lua_pushstring(L, argv[i]);
        }
        lua_pcall(L, argc, 0, 0);
    } else {
        cout << "ERR: can't find function \"MainEntry\"" << endl;
    }
 
    return 0;
}
2. [文件] lua_functions.cpp ~
#include <iostream>
#include <lua.hpp>
#include "type.h"
 
using namespace std;
 
/**
 * define all C lua functions below
 */
int l_hello(lua_State *L)
{
    cout << "Hello! This is C function." << endl;
}
 
/// add function and name in below table.
lua_register_t lua_cfunction_list [] = {
    "hello", l_hello,
    NULL
};
3. [文件] type.h ~ 
#ifndef __LUA_TYPE_H__
#define __LUA_TYPE_H__
 
#include <lua.hpp>
 
struct lua_register_t { 
    const char *name;
    lua_CFunction pfunc;
};
 
#endif  //__LUA_TYPE_H__
4. [文件] util.h ~ 
#ifndef __UTIL_H__
#define __UTIL_H__
 
#include <vector>
#include <string>
 
using namespace std;
 
extern void find_files(const string &dir_path, const string &part_name, vector<string> &file_list);
 
#endif  //__UTIL_H__
5. [文件] util.cpp ~
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
 
#include "util.h"
 
void find_files(const string &dir_path, const string &part_name, vector<string> &file_list)
{http://www.enterdesk.com/special/shouhui/​
    DIR *dir = opendir(dir_path.c_str());
    if (dir) {手绘图片
        struct stat statbuf;
        struct dirent *entry = NULL;
 
        while ((entry = readdir(dir)) != NULL) {
            string entry_name(entry->d_name);
 
            lstat(entry->d_name, &statbuf);
            if (S_ISDIR(statbuf.st_mode)) {
                if (entry_name == "." || entry_name == "..")
                    continue;
                find_files(dir_path + entry_name + '/', part_name, file_list);
            }
 
            size_t pos = entry_name.find(part_name);
            if (pos != std::string::npos) {
                string file_full_name = dir_path + entry_name;
                file_list.push_back(file_full_name);
            }
        }
        closedir(dir);
    }
}
6. [文件] Makefile.txt ~

Target = run_lua
Lib = lua_cfunc.a
 
CC = g++
AR = ar
 
all : lua_functions.o lib
    $(CC) -o $(Target) -lm lua_functions.o $(Lib) /usr/local/lib/liblua.a
 
lib : main.o util.o
    $(AR) crv $(Lib) main.o util.o
 
%.cpp: %o
    $(CC) -c $<
 
main.o : main.cpp type.h util.h
util.o : util.cpp util.h
lua_functions.o : lua_functions.cpp type.h
 
clean:
    rm *.o
7. [文件] main.lua ~ 181B     
print("loading files ...");
 
function MainEntry(...)
    print("This is MainEntry()")
    hello()
    for i, v in ipairs(arg) do
        print(i .. "=" .. tostring(v))
    end
end
​8.代码

[README]
 
main.cpp    --主函数文件,在main()中包含了导入库、注册C函数、导入LUA文件操作,最后调用MainEntray()函数。 
util.h util.cpp --定义find_files()函数,该函数功能是查找指定目录下的文件名,返回vector<string>
type.h      --定义lua_cfunction_table函数注册列表
lua_functions.cpp   --定义C函数,添加新的C函数库则加在这个文件里,不需要改动其它。
 
run_lua     --编译生成的可执行文件
            --执行该文件,注册lua_functions.cpp中所有的C函数,递归加载当前目录下所有*.lua文件,调用MainEntry()

Lua调用C,C++函数案例的更多相关文章

  1. lua调用的c函数模块命名规则

    比如lua中调用C函数 socket.core() , 在c中需要这样命名:luaopen_socket_core(); 基本模式是添加luaopen_前缀,讲.变为_

  2. Lua 调用的 C 函数保存 state 的两种方式: Storing State in C Functions 笔记

    http://yanbin.is-programmer.com/posts/94214.html Registery的Key 1. 整数Key用于Lua的引用机制,所以不要使用整数作为Key 2. 通 ...

  3. 【转】Cocos2d-x下Lua调用自定义C++类和函数的最佳实践

    转自:http://segmentfault.com/blog/hongliang/1190000000631630 关于cocos2d-x下Lua调用C++的文档看了不少,但没有一篇真正把这事给讲明 ...

  4. Step By Step(Lua调用C函数)

    原文: http://www.cnblogs.com/stephen-liu74/archive/2012/07/23/2469902.html Lua可以调用C函数的能力将极大的提高Lua的可扩展性 ...

  5. cocos进阶教程(1)Lua调用自定义C++类和函数的最佳实践

    第一层:纯C环境下,把C函数注册进Lua环境 a.lua 文件 )) a.c 文件 #include <lua.h> #include <lualib.h> #include ...

  6. Cocos2d-x下Lua调用自定义C++类和函数的最佳实践[转]

    Cocos2d-x下Lua调用C++这事之所以看起来这么复杂.网上所有的文档都没讲清楚,是因为存在5个层面的知识点: 1.在纯C环境下,把C函数注册进Lua环境,理解Lua和C之间可以互相调用的本质 ...

  7. lua调用c++函数返回值作用

    2015/05/28 lua调用c++接口,返回给lua函数的是压入栈的内容,可以有多个返回值.但是c++接口本身也是有返回值的,这个返回值也非常的重要,会决定最后返回到lua函数的值的个数. (1) ...

  8. lua入门之二:c/c++ 调用lua及多个函数返回值的获取

    当 Lua 调用 C 函数的时候,使用和 C 调用 Lua 同样类型的栈来交互. C 函数从栈中获取她的參数.调用结束后将返回结果放到栈中.为了区分返回结果和栈中的其它的值,每一个 C 函数还会返回结 ...

  9. lua调用c函数

    参考:http://blog.163.com/madahah@126/blog/static/170499225201121504936823/ 1.编辑C程序 vim luac.c #include ...

随机推荐

  1. 协程(Coroutine)并不是真正的多线程(转)

    自:http://www.zhihu.com/question/23895384 说到Coroutine,我们必须提到两个更远的东西.在操作系统(os)级别,有进程(process)和线程(threa ...

  2. LeetCode Recover Binary Search Tree——二查搜索树中两个节点错误

    Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing ...

  3. 【转载】ASP.Net WebForm温故知新学习笔记:一、aspx与服务器控件探秘

    开篇:毫无疑问,ASP.Net WebForm是微软推出的一个跨时代的Web开发模式,它将WinForm开发模式的快捷便利的优点移植到了Web开发上,我们只要学会三步:拖控件→设属性→绑事件,便可以行 ...

  4. 单点登录系统cas资料汇总

    http://jasig.github.io/cas/4.0.x/index.html           主页 https://jasigcas.herokuapp.com              ...

  5. jquery垂直滚动插件一个参数用于设置速度,兼容ie6

    利用外层的块级元素负外边距来滚动 1.使用 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://ww ...

  6. Effective Java - [3. 对象通用方法]

    Item 10. 若覆盖equals方法,需要遵守规则

  7. Java各类格式转换

    1.Java 根据固定格式的Excel生成实体类 2.GPS 经纬度转换为 经过旋转后的平面坐标

  8. yum 安装 mysql5.5 mysql 5.6 mysql5.7

      一. yum 安装mysql5.6 1. 安装仓库 要使用yum 安装mysql,需要使用mysql的yum 仓库,先从官网下载适合你的系统仓库 http://dev.mysql.com/down ...

  9. PHP购物车模块的实现(php/ajax/session)

    购物车网页代码 1.登录界面login.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ...

  10. 【BZOJ4052】[Cerc2013]Magical GCD 乱搞

    [BZOJ4052][Cerc2013]Magical GCD Description 给出一个长度在 100 000 以内的正整数序列,大小不超过 10^12.  求一个连续子序列,使得在所有的连续 ...