首页 > 代码库 > lua笔记之userdata

lua笔记之userdata

1.一直使用框架里封装好的c库,想着自己一点一点的写些例子,学习下,以后需要c库,可以自己写了。

下边是一个简单的userdata的例子--数组操作。

newarray.c

#include "lua.h"#include "lauxlib.h"#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <string.h>typedef struct NumArray{    int size;    double values[1];}NumArray;static int lnew(lua_State *L){    int arr_size = luaL_checkint(L, 1);    if (arr_size <= 0)    {        assert(NULL);    }    size_t nbytes = sizeof(NumArray) + (arr_size - 1) * sizeof(double);    NumArray *na = (NumArray *)lua_newuserdata(L, nbytes);    na->size = arr_size;    return 1;}static int lset(lua_State *L){    NumArray *na = (NumArray *)lua_touserdata(L, 1);    int idx = luaL_checkint(L, 2);    double value = http://www.mamicode.com/luaL_checknumber(L, 3);    printf("idx %d, value %f\n", idx, value);    luaL_argcheck(L, na != NULL, 1, "array expected");    luaL_argcheck(L, 1 <= idx && idx <= na->size , 2, "index out of range");    na->values[idx - 1] = value;    return 0;}static int lget(lua_State *L){    NumArray *na = (NumArray *)lua_touserdata(L, 1);    int idx = luaL_checkinteger(L, 2);    luaL_argcheck(L, na != NULL, 1, "array expected");    luaL_argcheck(L, 1 <= idx && idx <= na->size, 2, "index out of range");    lua_pushnumber(L, na->values[idx - 1]);    return 1;}        static intlfind(lua_State *L){    NumArray *na = (NumArray *)lua_touserdata(L, 1);    assert(na != NULL);    double elem = luaL_checknumber(L, 2);    int idx;    for (idx = 0; idx < na->size; idx++)    {        if (na->values[idx] == elem)        {            lua_pushnumber(L, idx + 1);            return 1;        }    }    lua_pushnumber(L, -1);    return 1;}intluaopen_newarray(lua_State *L){    luaL_checkversion(L);    luaL_Reg l[] =     {        {"new", lnew},        {"set", lset},        {"get", lget},        {"find", lfind},        {NULL, NULL},    };    luaL_newlib(L, l);    return 1;}

编译这个c文件,生成动态库 , 命令: gcc -O2 -g -Wall -shared -fPIC -o newarray.so newarray.c -I/usr/include/lua5.2 -llua5.2当然我这里用的是lua5.2,用其它版本的需要更改-I,和-l的头文件和链接库的内容。

测试代码:test.lua

local newarray = require "newarray"print(newarray)local na = newarray.new(1000)newarray.set(na, 1, 100)local value = newarray.find(na, 100)if value ~= -1 then    print("value is ", value)else    print("not exists")end

编译好newarray动态库,就可以运行测试代码了,安装lua是,编译后在src文件下有lua可执行文件,带着这个运行 ./.../lua test.lua.

结果如下:

技术分享

先让程序跑起来,理解。

后续会加上详细讲解.望多多提意见,指正。。

 

lua笔记之userdata