原文地址:http://blog.csdn.net/skyremember/article/details/3093195
api.cpp
#include <dirent.h>
#include "main.hpp"

int lua_getcwd(lua_State* L)//获取当前工作目录
{
char path[MAXPATHLEN];
bzero(path, MAXPATHLEN);
if (lua_gettop(L) != 0 ) //不需要参数
{
luaL_argerror(L, 0, "no arg expected");
return 0;
}
if ( !getcwd(path, MAXPATHLEN) )
{
luaL_error(L, "getcwd error %d, %s", errno, strerror(errno));
return 0;
}
lua_pushlstring(L, path, strlen(path));//将返回值压栈
return 1;//返回返回值个数
}

int lua_dir(lua_State* L)//取得目录下元素
{
const char* path = luaL_checkstring(L, 1);
DIR* dir = opendir(path);
if ( !dir )
{
lua_pushnil(L);
lua_pushstring(L, strerror(errno));
return 2;
}
int i = 1;
struct dirent *ent;
lua_newtable(L);//把所有元素放到一个table中,以数组返回
while( ent = readdir(dir) )
{
lua_pushnumber(L, i++);
lua_pushstring(L, ent->d_name);
lua_settable(L, -3);
}
closedir(dir);
return 1;
}

void register_api(lua_State* L)//注册api
{
lua_register(L, "getcwd", lua_getcwd);//脚本中可以使用getcwd调用lua_getcwd
lua_register(L, "dir", lua_dir);
const luaL_Reg mylib[] =
{
{"getcwd", lua_getcwd},
{"dir", lua_dir},
{NULL, NULL},
};
luaL_register(L, "tlib", mylib);//注册一个名为tlib的模块,tlib.getcwd()
}

void create_table(lua_State* L)//创建一个table
{
lua_newtable(L);
lua_pushnumber(L, 123);
lua_setfield(L, -2, "id");
lua_pushcfunction(L, lua_getcwd);
lua_setfield(L, -2, "fun");
lua_setglobal(L, "tb");
}
init.lua
function __init__()
print("__init__ ok")
return 1;
end
Makefile
CPPFLAGS=-Wall -g -O0 -I /usr/local/include/lua51/
LIB=-L/usr/local/lib/lua51/ -llua -lreadline
CC=g++

SRC=main.cpp api.cpp

OBJ=${SRC:%.cpp=%.o}

all: depend main

depend:
@$(CC) -MM $(SRC) > .depend
-include .depend

main: $(OBJ)
$(CC) $(OBJ) $(CPPFLAGS) $(LIB) -o $@

clean:
-rm -rf *.o main .depend
以上代码在freebsd 6.2 gcc 3.4.6 lua 5.1.2下编译通过。
阅读(865) | 评论(0) | 转发(0) |