给LUA添加自己的函数库

本文介绍了如何为 Lua 添加自定义函数库,以实现目录遍历功能。通过编写 util.c 文件,包含 util_findfirst、util_findnext 和 util_findclose 函数,实现了类似于 C 的 _findfirst、_findnext 和 _findclose 功能。接着在 lualib.h 中声明库函数,并在 init.c 中注册库。最后给出使用示例,展示了如何在 Lua 程序中调用这些自定义的文件遍历函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近几天,由于需要一组目录遍历的 函数,但标准库里面并没有提供,所以才有自己写一组:

1、添加一个util.c文件,文件内容如下:

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>

#define lutillib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"

static int util_findfirst(lua_State *L)
{
    const char *filename = luaL_checkstring(L, 1);
    luaL_Buffer b;
    luaL_buffinit(L, &b);
    struct _finddata_t fd;
    long pos = _findfirst(filename, &fd);
    if (pos)
    {
        lua_Integer f, type;
        f = pos;
        type = fd.attrib;
        lua_pushinteger(L, f);
     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值