Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify/override how numbers get stringified in Lua #183

Closed
cableray opened this issue Aug 6, 2020 · 2 comments
Closed

Modify/override how numbers get stringified in Lua #183

cableray opened this issue Aug 6, 2020 · 2 comments
Labels

Comments

@cableray
Copy link

cableray commented Aug 6, 2020

I am trying to change from a C runtime to a JS runtime, and am running into issues with the int32 type. Lua code which I can't modify is concatenating "33 bit" numbers (>= 2^31) to strings. Lua correctly internally represents these as floats, but somewhat annoyingly stringifies them with a trailing .0 when concatenating. This is annoying because it causes differences in output compared to the C Lua that I was previously using as the runtime. So I was trying to solve this, and was curious if there might be some way to change how numbers get stringified. Can I somehow modify this behavior, so that for large floats lua drops the trailing .0 if there is no fractional part? I'd like to do this without having to modify my existing code (except for maybe modifying _G or simmilar before my code runs) in any way. That means solutions like wrapping numeric values with string.format('%.0f', foo) unfourtunately don't work for my use case.

Javascript BigInts (#128) might work when implemented, but I'm looking for an immediate solution if available.

For more context, see here on stack overflow

@daurnimator
Copy link
Member

daurnimator commented Aug 6, 2020

fengari's behaviour intentionally matches Lua 5.3 here. See LUA_COMPAT_FLOATSTRING and https://www.lua.org/source/5.3/lobject.c.html#luaO_tostring
and the matching fengari code:

fengari/src/lobject.js

Lines 592 to 594 in 0c9631c

if (!LUA_COMPAT_FLOATSTRING && /^[-0123456789]+$/.test(str)) { /* looks like an int? */
str += '.0'; /* adds '.0' to result: lua_getlocaledecpoint removed as optimisation */
}

This is documented here:

fengari/src/luaconf.js

Lines 123 to 129 in 0c9631c

/*
@@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a
@@ a float mark ('.0').
** This macro is not on by default even in compatibility mode,
** because this is not really an incompatibility.
*/
const LUA_COMPAT_FLOATSTRING = conf.LUA_COMPAT_FLOATSTRING || false;

@cableray
Copy link
Author

cableray commented Aug 6, 2020

That solves my issue nicely.

@cableray cableray closed this as completed Aug 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants