Re: example of C types as a substitute for standard Lua types, without using any C function

  • From: "Robert G. Jakabosky" <bobby@xxxxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Mon, 6 Aug 2012 18:02:44 -0700

On Monday 06, razorcam razorcam wrote:
> --second version, with more boring ffi stuff at first, but then a
> nicer constructor syntax with no need for new()
> local ffi=require("ffi")
> ffi.cdef[[
> typedef struct {int32_t i;} int_c; //you can use any C type, but if
> you use int instead of int32_t then the number of bits will be
> platform dependent
> ]]
> local mt ={}
> local int=ffi.metatype("int_c",mt)
> --end of the boring ffi stuff, you can copy/paste it each time you
> want to use a C type
> local i=int(5)  --why 5 ? Because I like the number 5 :), otherwise it
> seems to default to zero
> while i.i<999999999 do i.i=i.i+1 end  -- on my Intel Atom, C integers
> are faster than the only standard number type of Lua, which is a
> floating number
> print(i.i)

Also you don't need the structure to use a simple C type:

local ffi=require"ffi"
-- define a nice constructor
local int = ffi.typeof("int32_t")

local i = int(5) -- make a 'int32_t' C type
while i<999999999 do i=i+1 end

Robert G. Jakabosky

Other related posts: