【问题标题】:Can I run a function for the Lua shell prompt?我可以为 Lua shell 提示符运行一个函数吗?
【发布时间】:2021-02-05 00:38:00
【问题描述】:

我可以用_PROMPT = "> "设置提示,但是我可以每次都更新提示吗?

我试过了,但它不起作用:

i = 0

function inc()
    i = i + 1
    return i
end

_PROMPT = inc

这显示_PROMPT,但没有任何相关:

for k, v in pairs(_G) do
    print(k)
end

【问题讨论】:

  • 不幸的是,_PROMPT 包含在for k, v in pairs(_G) do print(k) end 的输出中的唯一原因是因为我自己设置了它。因此,我无法使用此方法找到任何特殊变量。
  • lua -i -e "_PROMPT = 'A > ' ; _PROMPT2 = 'B >> '"

标签: function lua command-prompt


【解决方案1】:

主要提示是全局变量_PROMPT的值,如果这个值是一个字符串;否则,使用默认提示。

https://www.lua.org/manual/5.1/lua.html

你为_PROMPT分配了一个函数。

我试过了

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

,但没有运气,尽管每次我输入 = _PROMPT 时,_PROMPT 都会增加。

UPD 但这可以做到!在 Lua 邮件列表中,我被建议使用

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

它有效。这实际上是一种在更深层次上覆盖任何全局变量的方法,而不是简单地为其分配一个新值,或者使一组全局变量有效地无限。

您可以使用单线以交互模式启动 Lua:

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

【讨论】:

    【解决方案2】:

    我找到了debug.sethook()的方法。
    听起来有点奇怪,但其实很简单 ;-)
    来了……

    # /usr/bin/lua -i
    Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
    > debug.sethook(function(...) _PROMPT=os.date('%H:%M:%S # ') end,'r')
    10:49:42 # -- Hiting ENTER some times
    10:51:00 #
    10:51:01 #
    10:51:05 #
    

    (使用 Lua 5.3.5 完成并测试 5.4 - 应该使用 5.1 但未测试)
    'r' 表示:每次返回时触发

    编辑
    另一种方式直接用_PROMPT_PROMPT2...

    -- Simple method for changing and/or time logging the prompts                                                                                                                                 
    _PROMPT=setmetatable({},{__index=table})                                                                                                                                                                   
    _PROMPT2=setmetatable({},{__index=table})                                                                                                                                                                  
    
    getmetatable(_PROMPT).__tostring=function()
    _PROMPT:insert(os.date('%H:%M:%S',os.time())..'> ')
    return string.format('%s',_PROMPT:concat(#_PROMPT,#_PROMPT))
    end                              
    
    getmetatable(_PROMPT2).__tostring=function()
    _PROMPT2:insert(os.date('%H:%M:%S',os.time())..'>> ')
    return string.format('%s',_PROMPT2:concat(#_PROMPT2,#_PROMPT2))
    end
    

    ...使用 __tostring 和 __index 有 table 元方法。

    ...很有趣,保持健康。

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多