Class: Rufus::Lua::State

Included Modules

Rufus::Lua::StateMixin

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

Constructor Summary

public initialize(include_libs = true)

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’.

[View source]


376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/rufus/lua/state.rb', line 376

def initialize (include_libs=true)

  @pointer = Lib.luaL_newstate

  Array(include_libs).each do |libname|

    if libname == false
      break
    elsif libname == true
      Lib.luaL_openlibs(@pointer)
      break
    else
      Lib.send("luaopen_#{libname}", @pointer)
    end
  end

  #
  # 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 = []
end

Public Visibility

Public Instance Method Summary

#[](k)

Returns a value set at the ‘global’ level in the state.

#[]=(k, v)

Allows for setting a Lua varible immediately.

#close

Closes the state.

#eval(s)

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

#function(name, opts = {}, &block)

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

#gc_collect!

Runs garbage collection.

#gc_count

Returns current amount of memory in KB in use by Lua.

#gc_resume

Restart garbage collection for this state.

#gc_stop

Stop garbage collection for this state.

Public Instance Method Details

[]

public [](k)

Returns a value set at the ‘global’ level in the state.

  state.eval('a = 1 + 2')
  puts state['a'] # => "3.0"
[View source]


419
420
421
422
# File 'lib/rufus/lua/state.rb', line 419

def [] (k)

  k.index('.') ? self.eval("return #{k}") : get_global(k)
end

[]=

public []=(k, v)

Allows for setting a Lua varible immediately.

  state['var'] = [ 1, 2, 3 ]
  puts state['var'].to_a[0] # => 1
[View source]


429
430
431
432
433
# File 'lib/rufus/lua/state.rb', line 429

def []= (k, v)

  #puts; puts("#{k} = #{Rufus::Lua.to_lua_s(v)}")
  self.eval("#{k} = #{Rufus::Lua.to_lua_s(v)}")
end

close

public close

Closes the state.

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

[View source]


553
554
555
556
557
558
# File 'lib/rufus/lua/state.rb', line 553

def close

  raise "State already closed" unless @pointer
  Lib.lua_close(@pointer)
  @pointer = nil
end

eval

public eval(s)

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

[View source]


409
410
411
412
# File 'lib/rufus/lua/state.rb', line 409

def eval (s)

  loadstring_and_call(s)
end

function

public function(name, opts = {}, &block)

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

  require 'rubygems'
  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
[View source]


477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/rufus/lua/state.rb', line 477

def function (name, opts={}, &block)

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

  to_ruby = opts[:to_ruby]

  callback = Proc.new do |state|

    args = []

    loop do

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

      arg = stack_fetch
      break if arg.class == Rufus::Lua::Function

      args.unshift(arg)

      stack_unstack unless args.first.is_a?(Rufus::Lua::Table)
    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

    result = block.call(*args)

    stack_push(result)

    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!

public gc_collect!

Runs garbage collection

[View source]


570
571
572
573
574
# File 'lib/rufus/lua/state.rb', line 570

def gc_collect!

  raise "State got closed, cannot proceed" unless @pointer
  Lib.lua_gc(@pointer, LUA_GCCOLLECT, 0)
end

gc_count

public gc_count

Returns current amount of memory in KB in use by Lua

[View source]


562
563
564
565
566
# File 'lib/rufus/lua/state.rb', line 562

def gc_count

  raise "State got closed, cannot proceed" unless @pointer
  Lib.lua_gc(@pointer, LUA_GCCOUNT, 0)
end

gc_resume

public gc_resume

Restart garbage collection for this state

[View source]


586
587
588
589
590
# File 'lib/rufus/lua/state.rb', line 586

def gc_resume

  raise "State got closed, cannot proceed" unless @pointer
  Lib.lua_gc(@pointer, LUA_GCRESTART, 0)
end

gc_stop

public gc_stop

Stop garbage collection for this state

[View source]


578
579
580
581
582
# File 'lib/rufus/lua/state.rb', line 578

def gc_stop

  raise "State got closed, cannot proceed" unless @pointer
  Lib.lua_gc(@pointer, LUA_GCSTOP, 0)
end
Generated on Wednesday, September 30 2009 at 01:27:08 PM by YARD 0.2.3.5 (ruby-1.8.7).