Scite Lua Prompt

lua-users home
wiki

交互式 SciTE Lua

这是一个使用 SciteExtMan 脚本管理器的小脚本,也是下载中的示例之一。

它使用 extman 的 scite_OnOutputLine 事件来捕获 SciTE 输出窗格中输入的行,并使用 loadstring 进行编译。它为您提供了一种非常方便的方式来交互式地评估 Lua 表达式。可以定义单行函数。

Scite/Lua
> = 10 + 20
30
> print 'hello dolly'
hello dolly
> function showkeys(t) for i in t do print(i) end end
> showkeys(table)
setn
insert
getn
foreachi
foreach
sort
remove
concat
> 

即使您不认为自己会进行 Lua 编程,这个 Lua Prompt 也可以作为一个智能计算器非常有用。

任何全局函数都可用。提供了一个名为 load 的函数,该函数将从文件中加载 Lua 代码。如果调用时不带参数,它将使用当前缓冲区。函数 edit 将在新缓冲区中打开指定的文件。可以使用 Tools|Last Command(即 Ctrl-Alt-P)访问下拉式历史记录列表。

它对于学习 SciTE 和 Scintilla API 尤其有用,因为 editoroutput 窗格对象都可直接访问。您可以在编写完整的脚本之前测试特定操作。

> = output.Length
405
> output:AppendText('hello, world!\n')
hello, world!
> 

问题

对于那些期望全局对象在整个会话中都能保留的人来说,SciTE Lua 环境有一个令人头疼的惊喜。如果您在 SciTE 中切换缓冲区,全局环境会被清除。只有在通过 Lua 启动脚本加载的文件中最初创建的全局对象才能被保留。

源代码

源代码位于 Files:wiki_insecure/editors/SciTE/extman.zip

 -- prompt.lua
 scite_Command('Last Command|do_command_list|Ctrl+Alt+P')

 local prompt = '> '
 local history_len = 4
 local prompt_len = string.len(prompt)
 print 'Scite/Lua'
 trace(prompt)

 function load(file)
	if not file then file = props['FilePath'] end
	dofile(file)
 end

 function edit(file)
	scite.Open(file)
 end

 local sub = string.sub
 local commands = {}

 local function strip_prompt(line)
   if sub(line,1,prompt_len) == prompt then
        line = sub(line,prompt_len+1)
    end	
	return line
 end
  
 scite_OnOutputLine (function (line)
	line = strip_prompt(line)
   table.insert(commands,1,line)
    if table.getn(commands) > history_len then
        table.remove(commands,history_len+1)
    end
    if sub(line,1,1) == '=' then
        line = 'print('..sub(line,2)..')'
    end    
    local f,err = loadstring(line,'local')
    if not f then 
      print(err)
    else
      local ok,res = pcall(f)
      if ok then
         if res then print('result= '..res) end
      else
         print(res)
      end      
    end
    trace(prompt)
    return true
end)

function insert_command(cmd)
	output:AppendText(cmd)
	output:GotoPos(output.Length)
end

function do_command_list()
     if table.getn(commands) > 1 then 
		scite_UserListShow(commands,1,insert_command)
     end
end

RecentChanges · preferences
编辑 · 历史记录
最后编辑于 2006 年 11 月 15 日 上午 5:34 GMT (差异)