class Rufus::Lua::State

A Lua state, wraps a Lua runtime.

require 'rufus/lua'
s = Rufus::Lua::State.new
s.eval "a = 1 + 2"

p s['a'] # => 3.0

Public Class Methods

new(include_libs=true) click to toggle source

Instantiates a Lua state (runtime).

Accepts an 'include_libs' optional arg. When set to true (the default, all the base Lua libs are loaded in the runtime.

This optional arg can be set to false, when no libs should be present, or to an array of libs to load in order to prepare the state.

The list may include 'base', 'package', 'table', 'string', 'math', 'io', 'os' and 'debug'.

# File lib/rufus/lua/state.rb, line 377
def initialize(include_libs=true)

  @pointer = Lib.luaL_newstate

  open_libraries(include_libs)

  #
  # preparing library methods cache

  class << @pointer
    attr_reader :__lib_method_cache
  end
  @pointer.instance_variable_set(:@__lib_method_cache, {})

  #
  # an array for preserving callback (Ruby functions) from Ruby
  # garbage collection (Scott).

  @callbacks = []

  @error_handler = 0
end

Public Instance Methods

[](k) click to toggle source

Returns a value set at the 'global' level in the state.

state.eval('a = 1 + 2')
puts state['a'] # => "3.0"
# File lib/rufus/lua/state.rb, line 441
def [](k)

  k.index('.') ?  self.eval("return #{k}") : get_global(k)
end
[]=(k, v) click to toggle source

Allows for setting a Lua varible immediately.

state['var'] = [ 1, 2, 3 ]
puts state['var'].to_a[0] # => 1
# File lib/rufus/lua/state.rb, line 451
def []=(k, v)

  #puts; puts("#{k} = #{Rufus::Lua.to_lua_s(v)}")
  self.eval("#{k} = #{Rufus::Lua.to_lua_s(v)}")
end
close() click to toggle source

Closes the state.

It's probably a good idea (mem leaks) to close a Lua state once you're done with it.

# File lib/rufus/lua/state.rb, line 574
def close

  fail 'State already closed' unless @pointer
  Lib.lua_close(@pointer)
  @pointer = nil
end
eval(s, bndng=nil, filename=nil, lineno=nil) click to toggle source

Evaluates a piece (string) of Lua code within the state.

# File lib/rufus/lua/state.rb, line 431
def eval(s, bndng=nil, filename=nil, lineno=nil)

  loadstring_and_call(s, bndng, filename, lineno)
end
function(name, opts={}, &block) click to toggle source

Binds a Ruby function (callback) in the top environment of Lua

require 'rufus/lua'

s = Rufus::Lua::State.new

s.function 'key_up' do |table|
  table.inject({}) do |h, (k, v)|
    h[k.to_s.upcase] = v
  end
end

p s.eval(%{
  local table = {}
  table['CoW'] = 2
  table['pigs'] = 3
  table['DUCKS'] = 'none'
  return key_up(table)
}).to_h
  # => { 'COW' => 2.0, 'DUCKS => 'none', 'PIGS' => 3.0 }

s.close

:to_ruby => true

Without this option set to true, Lua tables passed to the wrapped Ruby code are instances of Rufus::Lua::Table. With this option set, rufus-lua will call to_ruby on any parameter that responds to it (And Rufus::Lua::Table does).

s = Rufus::Lua::State.new

s.function 'is_array', :to_ruby => true do |table|
  table.is_a?(Array)
end

s.eval(return is_array({ 1, 2 }))
  # => true
s.eval(return is_array({ 'a' = 'b' }))
  # => false
# File lib/rufus/lua/state.rb, line 498
def function(name, opts={}, &block)

  fail 'please pass a block for the body of the function' unless block

  to_ruby = opts[:to_ruby]

  callback =
    Proc.new do |state|

      s = CallbackState.new(state)
      args = []

      loop do

        break if s.stack_top == 0 # never touch stack[0] !!

        arg = s.stack_fetch

        args.unshift(arg)

        s.stack_unstack unless args.first.is_a?(Rufus::Lua::Ref)
      end

      while args.size < block.arity
        args << nil
      end

      args = args.collect { |a| a.respond_to?(:to_ruby) ? a.to_ruby : a } \
        if to_ruby

      s.stack_push(block.call(*args))

      1
    end

  @callbacks << callback
    # preserving the callback from garbage collection

  name = name.to_s

  name, index =
    if ri = name.rindex('.')
      #
      # bind in the given table

      table_name = name[0..ri-1]

      t = self.eval("return #{table_name}") rescue nil

      raise ArgumentError.new(
        "won't create automatically nested tables"
      ) if (not t) and table_name.index('.')

      t = self.eval("#{table_name} = {}; return #{table_name}") \
        unless t

      t.send(:load_onto_stack)

      [ name[ri+1..-1], -2 ]

    else
      #
      # bind function at the global level

      [ name, LUA_GLOBALSINDEX ]
    end

  Lib.lua_pushcclosure(@pointer, callback, 0)
  Lib.lua_setfield(@pointer, index, name)
end
gc_collect!() click to toggle source

Runs garbage collection

# File lib/rufus/lua/state.rb, line 591
def gc_collect!

  fail 'State got closed, cannot proceed' unless @pointer
  Lib.lua_gc(@pointer, LUA_GCCOLLECT, 0)
end
gc_count() click to toggle source

Returns current amount of memory in KB in use by Lua

# File lib/rufus/lua/state.rb, line 583
def gc_count

  fail 'State got closed, cannot proceed' unless @pointer
  Lib.lua_gc(@pointer, LUA_GCCOUNT, 0)
end
gc_resume() click to toggle source

Restart garbage collection for this state

# File lib/rufus/lua/state.rb, line 607
def gc_resume

  fail 'State got closed, cannot proceed' unless @pointer
  Lib.lua_gc(@pointer, LUA_GCRESTART, 0)
end
gc_stop() click to toggle source

Stop garbage collection for this state

# File lib/rufus/lua/state.rb, line 599
def gc_stop

  fail 'State got closed, cannot proceed' unless @pointer
  Lib.lua_gc(@pointer, LUA_GCSTOP, 0)
end
open_libraries(libs) click to toggle source
# File lib/rufus/lua/state.rb, line 637
def open_libraries(libs)

  if libs == true
    Lib.luaL_openlibs(@pointer)
  elsif libs.is_a?(Array)
    libs.each { |l| open_library(l) }
  end
end
open_library(libname) click to toggle source

open_library(libname) - load a lua library via lua_call().

This is needed because is the Lua 5.1 Reference Manual Section 5 (www.lua.org/manual/5.1/manual.html#5) it says:

β€œThe luaopen_* functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function.”

β€œ..you must call them like any other Lua C function, e.g., by using lua_call.”

(by Matthew Nielsen - github.com/xunker)

# File lib/rufus/lua/state.rb, line 627
def open_library(libname)

  Lib.lua_pushcclosure(
    @pointer, lambda { |ptr| Lib.send("luaopen_#{libname}", @pointer) }, 0)
  Lib.lua_pushstring(
    @pointer, (libname.to_s == "base" ? "" : libname.to_s))
  Lib.lua_call(
    @pointer, 1, 0)
end
set_error_handler(lua_code=nil, &block) click to toggle source
# File lib/rufus/lua/state.rb, line 400
def set_error_handler(lua_code=nil, &block)

  if lua_code == nil && block

    function('_ruby_error_handler', &block)
    stack_load_path('_ruby_error_handler')
    @error_handler = stack_top

  elsif lua_code == nil

    Lib.lua_remove(@pointer, @error_handler) if @error_handler > 0
    @error_handler = 0

  elsif lua_code == :traceback

    stack_load_path('debug.traceback')
    @error_handler = stack_top

  else

    lua_code = lua_code.strip
    lua_code = 'return ' + lua_code unless lua_code.match(/^return\s+/)

    r = self.eval(lua_code)
    r.send(:load_onto_stack)
    @error_handler = stack_top
  end
end