rvirding / luerl

Lua in Erlang
Apache License 2.0
1.02k stars 140 forks source link

pcall and division by zero #146

Open iggi42 opened 2 years ago

iggi42 commented 2 years ago
crash = function()
  return 10/0
end
return pcall(crash)

This still crashes in luerl, ignoring the supposed protection of "pcall".

The official lua returns inf, when divided by zero. Pcall returns true here.

iggi42 commented 2 years ago

guess extending the numeric operators on how to handle "inf" would be the right move.

That is here, right? https://github.com/rvirding/luerl/blob/develop/src/luerl_emul.erl#L1020' sounds like a good first pr.

rvirding commented 2 years ago

The problem is that Erlang floating point doesn't "inf", if you divide by 0.0 you get a badarith error. There is nothing to do about this. I will check pcall though to see what is going on with it failing.

rvirding commented 2 years ago

The reason why pcall crashes is that by design it only catches Lua errors and and not Erlang errors and the badarith error generated by dividing by 0 is an Erlang error.

iggi42 commented 2 years ago

The problem is that Erlang floating point doesn't "inf", if you divide by 0.0 you get a badarith error. There is nothing to do about this.

I mean, we would need to extend what the internal representation of a number can be. like adding the :infinity atom. Lua also has a NaN, (resulting from inf - inf for example). probably want to add both of these in one go.

Alternatively maybe extend division with a clause to make it

op('/', A1, A2, St) ->
    numeric_op('/', A1, A2, St, <<"__div">>, fun (_,0) -> lua_error("dividing by 0 bad", St);
                                                                         (N1,N2) -> N1/N2 end);

Not sure if this would work.

iggi42 commented 2 years ago

like how close to the official lua c implementation is luerl supposed to be?

rvirding commented 1 year ago

As close as is reasonably possible using standard Erlang and OTP.