Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3214405
  • 博文数量: 685
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5303
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-19 14:17
个人简介

文章分类

全部博文(685)

文章存档

2015年(116)

2014年(569)

分类: 嵌入式

2014-08-28 10:59:50

原文地址: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) |
0

上一篇:lua源码赏析

下一篇:常用命令--开发必备

给主人留下些什么吧!~~