How to create c extension for lua and pass complex structure step by step

You could download the project from http://groups.google.com/group/lua5/web/luautil.rar

At first, create a windows dll application. The IDE I used is VC2008.

I suggest you download and install the "Lua for windows" from luaforge.net, it contains most useful packages for Lua windows development. You could copy "include" and "lib" directory under the installation directory to your project.

image

In the beginning, you should include Lua header files.

image

Please note, you should use extern "C" to declare the header for Lua. In linker’s input, set the lua51.lib.

image

The project should have a function like luaopen_xxx (in my code, it is luaopen_luautil), and have strings=>functions map structure like "lua_util". Then you could call your extension like require "luautil".

image

The L_MSleep will call windows’ api Sleep().

Another function L_NewTable will generate a complex table for Lua script. It will call lua_settable() and lua_setfield() function to manipulate the table in Lua. lua_pushstring() and lua_pushnumber() could push string type and number type data to Lua. You could find the document about these functions in Lua 5.1 manual.

You could use "lua2c" to get the result for generating lua table to c code. It is a helpful utility. http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lua2c

image

The table that Lua get will like:

local table1 = { 
           userName1 = "hahaha", 
           serialNumber1 = "1234613423", 
           tbl = {userName2 = "wwwww", serialNumber2 = "asdfasdadf", "5566", "wowowo"}}

After you build the project, copy the dll to lua installation folder "lua\5.1\clibs".

In the end, we could test the extension like:

require "luautil"
        local newtable =luautil.newtable()

for k, v in pairs(newtable) do
            print(k, v)
            if type(v) == "table" then
                for k2, v2 in pairs(v) do
                    print("–", k2, v2)
               end
           end
        end

– sleep 5 seconds.
         luautil.msleep(5000)

 

Tags : , ,

Google Reader Yahoo Facebook Twitter Digg FriendFeed Delicious Google Translate
这篇日志发表于2009年11月23日 7:57 下午。 你可以订阅该日志的所有评论通过 RSS 2.0。 你可以发表评论,或者引用通告

1条回应

评论(0)引用通告(1)

  1. [...] 在PIL以及Lua manual上介绍了如何使用c语言编写lua的第三方扩展,另外可以参考我的文章与示例代码http://sunxiunan.com/?p=1498 [...]

发表评论

(Ctrl+Enter)

XHTML:你可以使用这些标签:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>