Skip to content

Instantly share code, notes, and snippets.

@moxley
Last active January 4, 2016 10:09
Show Gist options
  • Save moxley/8606447 to your computer and use it in GitHub Desktop.
Save moxley/8606447 to your computer and use it in GitHub Desktop.
Convert Ruby data to formatted Lua code
# Convert Ruby data to formatted Lua code
# irb(main):001:0> load 'to_lua.rb'; puts ToLua.format(['what', "she's", nil, false, true, ['yep'], [], {}, {foo: 'foo'}, {'bar' => 'bar'}, {0 => 'zero'}])
# {'what', 'she\'s', nil, false, true, {'yep'}, {}, {}, {foo = 'foo'}, {['bar'] = 'bar'}, {[0] = 'zero'}}
module ToLua
extend self
# Format value
def format(v)
if v.kind_of?(Array)
format_array(v)
elsif v.kind_of?(Hash)
format_hash(v)
else
format_scalar(v)
end
end
def format_array(a)
'{' + a.map { |v| format(v) }.join(', ') + '}'
end
def format_hash(h)
'{' + h.map { |k, v| format_key(k) + ' = ' + format(v) }.join(', ') + '}'
end
def format_scalar(s)
if s == nil
"nil"
elsif s.kind_of?(Fixnum) || s.kind_of?(Float) || s.kind_of?(Symbol) || s == false || s == true
s.to_s
else
format_string(s)
end
end
def format_string(s)
"'" + s.to_s.gsub(/([\\'])/, '\\\\\1') + "'"
end
def format_key(k)
if k.kind_of?(Symbol)
k.to_s
else
'[' + format_scalar(k) + ']'
end
end
end
@maxjustus
Copy link

Agh, sorry. Key value tables aren't delimited with :. The syntax is

local t = {key = 123, key2 = 1234}
t.key -- will return 123

For string keys, you'd do

local t = {['key'] = 123, ['key2'] = 1234}
t['key'] -- will return 123

In this case, I think string keys might be the safest bet.

@moxley
Copy link
Author

moxley commented Jan 24, 2014

Ah, interesting. Will adjust...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment