Lua调用C,C++函数案例

该程序主要是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()