Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Treetop parser for Lua objects (limited)
LUAOBJECT_GRAMMAR = %q{
grammar LuaObject
rule luaobj
space value space { def to_ruby; value.to_ruby; end }
end
rule value
nil / float / number / string / table / boolean
end
rule nil
'nil' { def to_ruby; nil; end }
end
rule table
'{' space elementses:element* space '}' {
def to_ruby(*args)
temparray = elementses.elements.map { |x| x.to_ruby }
return LuaObjectParser.splash_array(temparray)
end
}
end
rule element
space elementv space (',' &element / !element) {
def to_ruby
elementv.to_ruby
end
}
end
rule elementv
key space '=' space value {
def to_ruby
hsh = { key.to_ruby => value.to_ruby }
def hsh.intermediate_hash?
true
end
hsh
end
}
/
value
end
rule key
word
/
'[' space value space ']' {
def to_ruby
value.to_ruby
end
}
end
rule float
[0-9]+ '.' [0-9]+ { def to_ruby; text_value.to_f; end }
end
rule number
[0-9]+ {
def to_ruby
text_value.to_i
end
}
end
rule string
'"' (!'"' . / '\"')* '"' {
def to_ruby
text_value[1..-2]
end
}
end
rule boolean
('true' / 'false') {
def to_ruby
text_value == 'true'
end
}
end
rule word
[A-Za-z_]+ {
def to_ruby
text_value
end
}
end
rule space
[ \t\r\n]*
end
end
}
File.open("luaobject.treetop","w") { |f| f << LUAOBJECT_GRAMMAR }
require 'treetop'
Treetop.load('luaobject')
class LuaObjectParser
##
# Converts an array to a hash or array depending on the
# contents. The parser returns an array mixed of PODs and Hashes. If
# there are hashes, convert everything to a hash and insert
# unindexed types with index as key.
def self.splash_array(ary)
if ary.find { |x| Hash === x and x.intermediate_hash? }
idx = 1
hsh = {}
def hsh.intermediate_hash?; false; end
ary.each { |x|
if Hash === x and x.intermediate_hash?
hsh[x.keys[0]] = x.values[0]
else
hsh[idx] = x
idx += 1
end
}
return hsh
else
return ary
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.