Class: Rufus::Lua::State

Inherits:
Object
  • Object
show all
Includes:
StateMixin
Defined in:
lib/rufus/lua/state.rb

Overview

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

Constant Summary

Constants included from StateMixin

Rufus::Lua::StateMixin::LUA_ENVIRONINDEX, Rufus::Lua::StateMixin::LUA_GLOBALSINDEX, Rufus::Lua::StateMixin::LUA_MULTRET, Rufus::Lua::StateMixin::LUA_NOREF, Rufus::Lua::StateMixin::LUA_REFNIL, Rufus::Lua::StateMixin::LUA_REGISTRYINDEX, Rufus::Lua::StateMixin::TBOOLEAN, Rufus::Lua::StateMixin::TFUNCTION, Rufus::Lua::StateMixin::TLIGHTUSERDATA, Rufus::Lua::StateMixin::TNIL, Rufus::Lua::StateMixin::TNONE, Rufus::Lua::StateMixin::TNUMBER, Rufus::Lua::StateMixin::TSTRING, Rufus::Lua::StateMixin::TTABLE, Rufus::Lua::StateMixin::TTHREAD, Rufus::Lua::StateMixin::TUSERDATA

Instance Method Summary collapse

Constructor Details

#initialize(include_libs = true) ⇒ State

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.



321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/rufus/lua/state.rb', line 321

def initialize (include_libs=true)

  @pointer = Lib.luaL_newstate

  Lib.luaL_openlibs(@pointer) if include_libs

  #
  # preparing library methods cache

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

Instance Method Details

#[](k) ⇒ Object

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

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


350
351
352
353
# File 'lib/rufus/lua/state.rb', line 350

def [] (k)

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

#closeObject

Closes the state.

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



361
362
363
364
# File 'lib/rufus/lua/state.rb', line 361

def close

  Lib.lua_close(@pointer)
end

#eval(s) ⇒ Object

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



339
340
341
342
# File 'lib/rufus/lua/state.rb', line 339

def eval (s)

  loadstring_and_call(s)
end