Permalink
Browse files

Implement table literals.

  • Loading branch information...
Twisol committed Feb 20, 2011
1 parent 14a7673 commit 51192de7d22ceb93685d4223c4ca8cb979c6cbb0
View
@@ -23,6 +23,5 @@ PLATFORMS
DEPENDENCIES
bundler (~> 1.0.0)
- citrus (~> 2.2.0)
lupin!
rspec (~> 2.2.0)
View
@@ -3,6 +3,8 @@ module Lupin
require "lupin/parser"
require "lupin/state"
+ # Evaluate a string as a chunk of Lua code.
+ # CAVEAT: Really only works for expressions right now.
def self.eval (state, str)
ast = Lupin::Parser.parse(str, :root => :expression)
state.compile(ast).call
View
@@ -1,15 +1,24 @@
module Lupin::AST
class Table
def initialize (fieldlist=[])
- @fields = fieldlist
+ @fields = {}
+ current_integer = 0
+ fieldlist.each do |k, v|
+ k ||= Lupin::AST::Literal.new(current_integer += 1)
+ @fields[k] = v
+ end
end
- def == (other)
- @fields == other.instance_variable_get(:@fields)
- end
-
- def [] (key)
- @fields[key]
+ def bytecode (g)
+ g.push_table
+
+ @fields.each do |k, v|
+ g.dup_top
+ k.bytecode(g)
+ v.bytecode(g)
+ g.set_table
+ g.pop
+ end
end
def sexp
View
@@ -11,6 +11,23 @@ def push_literal (arg)
g.push_literal(arg)
end
+ def push_table
+ g.push_literal Lupin::Types::Table
+ g.send :new, 0
+ end
+
+ def dup_top
+ g.dup
+ end
+
+ def pop
+ g.pop
+ end
+
+ def ret
+ g.ret
+ end
+
def add
math :+, '__add'
end
@@ -40,8 +57,8 @@ def concat
g.push_literal "Hello from the unfinished concatenation routine"
end
- def ret
- g.ret
+ def set_table
+ g.send :[]=, 2
end
def assemble (name, file, line)
View
@@ -6,6 +6,7 @@ module Lupin::Parser
Citrus.load(File.join(File.dirname(__FILE__), 'parser', 'parser'))
+ # Transform a chunk of Lua code into an AST.
def self.parse (subject, opts={}, *args, &blk)
Lua.parse(subject, {:consume => true}.merge(opts), *args, &blk).value
end
@@ -87,7 +87,7 @@ def value
module Pair
def value
- [k == '' ? Lupin::AST::Literal.new(nil) : k.value, v.value]
+ [k == '' ? nil : k.value, v.value]
end
end
end
@@ -4,7 +4,7 @@ grammar Lupin::Parser::Lua
end
rule chunk
- list:statement* { matches.map(&:value) }
+ list:statement* { matches.map {|stat| stat.value} }
end
rule statement
@@ -29,10 +29,10 @@ grammar Lupin::Parser::Lua
end
rule args
- ( ('(' WS? explist WS? ')' WS?) { explist.value }
- | ('(' WS? ')' WS?) { [] }
- | (table WS?) { [table] }
- | (string WS?) { [string] }
+ ( ('(' WS? explist WS? ')') { explist.value }
+ | ('(' WS? ')') { [] }
+ | (table) { [table] }
+ | (string) { [string] }
)
end
View
@@ -1,4 +1,21 @@
module Lupin::Types
class Table < Value
+ def initialize
+ @hash = {}
+ end
+
+ def [] (key)
+ @hash[key]
+ end
+
+ def []= (key, value)
+ @hash[key] = value
+ end
+
+ def to_s
+ str = '{'
+ str << @hash.to_a.map {|k, v| "[#{k}] = #{v}"}.join(', ')
+ str << '}'
+ end
end
end

0 comments on commit 51192de

Please sign in to comment.