Take into account __tostring whet printing _PROMPT

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Take into account __tostring whet printing _PROMPT

Александр Машин-2
Dear all,

Why doesn't interactive Lua takes into account the __tostring metamethod
of the non-string _PROMPT global when it prints the prompt, so that the
below code does not help to increment the prompt on any typed command,
although on any >=_PROMPT the variable is incremented?

|>_PROMPT = {no = 0}; setmetatable (_PROMPT, {__tostring = function
(self) self.no = self.no + 1; return tostring (self.no) .. ' >' end})|

https://stackoverflow.com/a/64474830/6632736


Alexander Mashin
Reply | Threaded
Open this post in threaded view
|

Re: Take into account __tostring whet printing _PROMPT

Marcus Mason
This should do what you want when evaluated in the REPL:

setmetatable(_ENV, {__index = function(t, k) if k == '_PROMPT' then t._N = (t._N or 0) + 1; return t._N .. ' >' end end})

On Thu, Oct 22, 2020 at 4:35 AM Александр Машин <[hidden email]> wrote:
Dear all,

Why doesn't interactive Lua takes into account the __tostring metamethod
of the non-string _PROMPT global when it prints the prompt, so that the
below code does not help to increment the prompt on any typed command,
although on any >=_PROMPT the variable is incremented?

|>_PROMPT = {no = 0}; setmetatable (_PROMPT, {__tostring = function
(self) self.no = self.no + 1; return tostring (self.no) .. ' >' end})|

https://stackoverflow.com/a/64474830/6632736


Alexander Mashin
Reply | Threaded
Open this post in threaded view
|

Re: Take into account __tostring whet printing _PROMPT

Александр Машин-2
22.10.2020 13:24, Marcus Mason пишет:
> setmetatable(_ENV, {__index = function(t, k) if k == '_PROMPT' then
> t._N = (t._N or 0) + 1; return t._N .. ' >' end end})

Thank you very much, it really works. Lua's is amazing in hiw deeply it
can be customized.


Alexander Mashin
Reply | Threaded
Open this post in threaded view
|

Re: Take into account __tostring whet printing _PROMPT

Luiz Henrique de Figueiredo
In reply to this post by Александр Машин-2
> Why doesn't interactive Lua takes into account the __tostring metamethod
> of the non-string _PROMPT global when it prints the prompt,

Replace get_prompt in lua.c by the code below and rebuild.
It seems to work, but it hasn't been thoroughly tested.
The original code uses lua_tostring, which does not honor the
__tostring metamethod; luaL_tolstring does.

static const char *get_prompt (lua_State *L, int firstline) {
  const char *p;
  if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL)
    p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  else {
    p = luaL_tolstring(L, -1, NULL);
    lua_remove(L, -2);  /* remove original value */
  }
  return p;
}