Skip to content

Commit

Permalink
Merge pull request #6 from ifu-hh/master
Browse files Browse the repository at this point in the history
Encode Strings with default external encoding
  • Loading branch information
whitequark committed May 20, 2016
2 parents 37cbaad + a0855c3 commit 80a4d77
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
12 changes: 8 additions & 4 deletions ext/rlua.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>
#include <ctype.h>
#include <ruby/encoding.h>

VALUE mLua, cLuaState, cLuaMultret, cLuaFunction, cLuaTable;

Expand Down Expand Up @@ -77,7 +78,7 @@ static VALUE rlua_get_var(lua_State *state)
size_t length;
const char* string;
string = lua_tolstring(state, -1, &length);
return rb_str_new(string, length);
return rb_enc_str_new(string, length, rb_default_external_encoding());
}

case LUA_TTABLE:
Expand All @@ -98,10 +99,13 @@ static void rlua_push_var(lua_State *state, VALUE value)
lua_pushnil(state);
break;

case T_STRING:
lua_pushlstring(state, RSTRING_PTR(value), RSTRING_LEN(value));
break;
case T_STRING: {
const char* string;
string = rb_str_export_to_enc(value, rb_default_external_encoding());

lua_pushlstring(state, RSTRING_PTR(string), RSTRING_LEN(string));
break;
}
case T_FIXNUM:
lua_pushnumber(state, FIX2INT(value));
break;
Expand Down
29 changes: 29 additions & 0 deletions spec/rlua_spec.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# encoding: utf-8
require 'rlua'

describe Lua::State do
Expand Down Expand Up @@ -37,5 +38,33 @@

expect(subject.ran).to be_truthy
end

context 'string encoding' do
before { Encoding.default_external = Encoding::UTF_8 }

it 'creates a string in Lua and pass it to Ruby with default_external encoding' do
subject.__eval 'value = "höhöhö"'

expect(subject.value).to eq 'höhöhö'
expect(subject.value.encoding).to eq Encoding::UTF_8
end

it 'creates a string in Lua and pass it to Ruby with custom default_external encoding' do
Encoding.default_external = Encoding::ISO8859_15

subject.__eval 'value = "höhöhö"'.encode(Encoding::ISO8859_15)

expect(subject.value).to eq 'höhöhö'.encode(Encoding::ISO8859_15)
expect(subject.value.encoding).to eq Encoding::ISO8859_15
end

it 'creates a string in Lua and pass it to Ruby with default_external encoding' do
subject.value = 'höhöhö'.encode(Encoding::EUCJP_MS)

expect(subject.value).to eq 'höhöhö'
expect(subject.value.encoding).to eq Encoding.default_external
end
end

end
end

0 comments on commit 80a4d77

Please sign in to comment.