lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 21.01.2011 20:06, Mike Pall wrote:

> FFI Library
> -----------
> 
> The FFI library allows calling external C functions and the use of C
> data structures from pure Lua code.
> 
> The FFI library largely obviates the need to write tedious manual
> Lua/C bindings in C. It doesn't require learning a separate binding
> language -- it parses plain C declarations, which can be cut-n-pasted
> from C header files or reference manuals (*). It's up to the task of
> binding large libraries without the need for dealing with fragile
> binding generators.

This is really great!
Some time ago I have ported simple SDL example to Lua using alien:

http://lua-users.org/lists/lua-l/2008-08/msg00310.html

Today I have made FFI version for comparison. It means:
- using gcc -E instead of manually defining function signatures
- no more defining constants in Lua code
- indexing structs with hash names instead of byte offsets
- no other major changes in the Lua code

It looks like it is far easier than using alien. It is a new era for Lua.

Here is the code:

#!/usr/bin/luajit2
-- Don't forget to generate *.h file:
-- $ echo '#include <SDL.h>' > stub.c
-- $ gcc -I /usr/include/SDL -E stub.c|grep -v '^#' > ffi_SDL.h
-- Run with luajit2 testsdl.lua
-- Ported to lua from:
-- http://gamedevgeek.com/tutorials/getting-started-with-sdl/

local ffi=require "ffi"
ffi.cdef( io.open('ffi_SDL.h', 'r'):read('*a'))

SDL=ffi.load('SDL')

SCREEN_WIDTH,SCREEN_HEIGHT=640,480

-- wrapper functions
function SDL_LoadBMP(file)
  return SDL.SDL_LoadBMP_RW(SDL.SDL_RWFromFile(file, "rb"), 1)
end
--
function SDL_BlitSurface(src, srcrect, dst, dstrect)
  return SDL.SDL_UpperBlit(src, srcrect, dst, dstrect)
end
--

-- Initialize SDL
local SDL_INIT_VIDEO=0x20
SDL.SDL_Init(SDL_INIT_VIDEO)

-- set the title bar
SDL.SDL_WM_SetCaption("SDL Test","SDL Test")

-- create window
local screen = SDL.SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0)

-- load bitmap to temp surface
local temp = SDL_LoadBMP('sdl_logo.bmp') -- get it from
http://gamedevgeek.com/f
iles/sdltest.tar.gz

-- convert bitmap to display format
local bg = SDL.SDL_DisplayFormat(temp)

-- free the temp surface
SDL.SDL_FreeSurface(temp);

local event=ffi.new("SDL_Event")

local gameover = false;

-- message pump
while not gameover do
  -- look for an event
  if SDL.SDL_PollEvent(event)==1 then
    -- an event was found
    local etype=event.type
    if etype==SDL.SDL_QUIT then
      -- close button clicked
      gameover=true
      break
    end

    if etype==SDL.SDL_KEYDOWN then
      -- handle the keyboard
      sym=event.key.keysym.sym

      if sym==SDL.SDLK_q or sym==SDL.SDLK_ESCAPE then
        gameover=true
        break
      end
    end

  end
  SDL_BlitSurface(bg, nil, screen, nil)
  SDL.SDL_UpdateRect(screen, 0,0,0,0)
end

Regards,
miko