Skip to content

Commit

Permalink
src/loslib.js: implement os.setlocale
Browse files Browse the repository at this point in the history
  • Loading branch information
daurnimator committed Mar 14, 2019
1 parent 9b4b687 commit c3bc19f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/loslib.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const {
luaL_argerror,
luaL_buffinit,
luaL_checkinteger,
luaL_checkoption,
luaL_checkstring,
luaL_checktype,
luaL_error,
Expand Down Expand Up @@ -451,9 +452,28 @@ const os_difftime = function(L) {
return 1;
};

const catnames = ["all", "collate", "ctype", "monetary", "numeric", "time"].map((lc) => to_luastring(lc));
const C = to_luastring("C");
const POSIX = to_luastring("POSIX");
const os_setlocale = function(L) {
const l = luaL_optstring(L, 1, null);
luaL_checkoption(L, 2, "all", catnames);
/* It is not possible to set the JS-VM wide locale, so we say that we only
know the C locale. The "POSIX" locale is defined in
IEEE Std 1003.1-2017 Section 7.2 as equivalent to "C" */
lua_pushstring(L, (
l === null /* passing nil returns the current locale; which is "C" */
|| l.length == 0 /* empty string resets to the default locale; which is "C" */
|| luastring_eq(l, C) /* user passed "C" */
|| luastring_eq(l, POSIX) /* user passed "POSIX", equivalent to "C" */
) ? C : null);
return 1;
};

const syslib = {
"date": os_date,
"difftime": os_difftime,
"setlocale": os_setlocale,
"time": os_time
};

Expand Down
17 changes: 17 additions & 0 deletions test/loslib.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,23 @@ test('os.time normalisation of table', () => {
});


test('os.setlocale', () => {
let L = lauxlib.luaL_newstate();
if (!L) throw Error("failed to create lua state");

let luaCode = `
assert("C" == os.setlocale())
assert("C" == os.setlocale(""))
assert("C" == os.setlocale("C"))
assert("C" == os.setlocale("POSIX"))
assert(nil == os.setlocale("any_other_locale"))
`;
lualib.luaL_openlibs(L);
expect(lauxlib.luaL_loadstring(L, to_luastring(luaCode))).toBe(lua.LUA_OK);
lua.lua_call(L, 0, 0);
});


test('os.getenv', () => {
let L = lauxlib.luaL_newstate();
if (!L) throw Error("failed to create lua state");
Expand Down

0 comments on commit c3bc19f

Please sign in to comment.