Last active
January 4, 2016 10:09
-
-
Save moxley/8606447 to your computer and use it in GitHub Desktop.
Convert Ruby data to formatted Lua code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Ah, interesting. Will adjust...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Agh, sorry. Key value tables aren't delimited with
:
. The syntax isFor string keys, you'd do
In this case, I think string keys might be the safest bet.