该程序主要是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. 分层架构web容器的配置安全

    转自:http://hi.baidu.com/shineo__o/item/7520d54c24d234c71081da82 /ps:本以为这是一个偶然配置失误造成的问题,但最近几天无聊时测试发现,有 ...

  2. 新版本号的tlplayer for android ,TigerLeapMC for windows公布了

    tlplayer for android 新版本号修正了图像倾斜等等问题,添加了动态水印功能. 支持hls(m3u8),http,rtsp,mms,rtmp等网络协议. 声明tlplayer 上的变速 ...

  3. IE对CSS样式的数量和大小的限制

    项目中遇到的问题,css写的样式无法渲染,各种百度后发现大概是这个原因: IE对CSS样式的数量和大小的限制 文档中只有前31个link或style标记关联的CSS能够应用. 从第32个开始,其标记关 ...

  4. 在C#中怎样推断线程当前所处的状态

    在C#中怎样推断线程当前所处的状态 老帅       在C#中.线程对象Thread使用ThreadState属性指示线程状态.它是带Flags特性的枚举类型对象.    ThreadState 为线 ...

  5. 笔记本中LVDS屏与eDP屏的比较

    LVDS,即Low Voltage Differential Signaling,是一种低压差分信号技术接口.它是美国NS公司(美国国家半导体公司)为克服以TTL电平方式传输宽带高码率数据时功耗大.E ...

  6. Lua学习六----------Lua流程控制

    © 版权声明:本文为博主原创文章,转载请注明出处 Lua流程控制 - 通过程序设定一个或多个条件语句 - 在条件为true时执行指定程序代码,在条件为false时指定其他指定程序代码 - 控制结构语句 ...

  7. rootkit基础

    应用程序总是离不开系统内核所提供的服务,比如它要使用内存的时候,只要跟操作系统申请就行了,而不用自己操心哪里有空闲的内存空间等问题,实际上,这些问题是由操作系统的内核来代劳的.站在黑客的角度讲,如果能 ...

  8. Django之forms表单类

    Form表单的功能 自动生成HTML表单元素 检查表单数据的合法性 如果验证错误,重新显示表单(数据不会重置) 数据类型转换(字符类型的数据转换成相应的Python类型) 1.创建Form类 from ...

  9. Chrome自带恐龙小游戏的源码研究(七)

    在上一篇<Chrome自带恐龙小游戏的源码研究(六)>中研究了恐龙的跳跃过程,这一篇研究恐龙与障碍物之间的碰撞检测. 碰撞盒子 游戏中采用的是矩形(非旋转矩形)碰撞.这类碰撞优点是计算比较 ...

  10. rtems 4.11 启动流程(arm, beagle)

    请参照官方的 bsp_howto 文档,对arm来说,首先执行的文件是start.S start.S c/src/lib/libbsp/arm/shared/start/start.S 1.从 _st ...