创建一个TCL解释器,它只支持我提供的命令

Nar*_*rek 5 interpreter tcl sandbox

假设我已经定义了proc f1 proc f2和proc f3.现在,我想创建一个TCL解释,PROC F1 PROC F2和F3 PROC的代码源成解释和限制比F1,F2等所有命令和F3是解释器中.我怎么能这样做?

编辑:

如果在解释器中调用了f1,f2和f3以外的命令,我已经创建了一个错误消息,并且应该在解释器中执行代码(假设这个另一个代码来源于同一个解释器,在获取之后应停止使用f1,f2和f3过程的代码.

Don*_*ows 9

你不能那么做,但你可以做一些与大多数目的相似的事情.

你应该做的是通常在解释器中创建命令f1,f2和f3,然后创建一个根本没有Tcl命令的子解释器,并将你想要在该子解释器中公开的命令别名化为命令在父母.

# First define f1-f3 in whatever way you want

# Now make the context; we'll use a safe interpreter for good measure...
set slave [interp create -safe]

# Scrub namespaces, then global vars, then commands
foreach ns [$slave eval namespace children ::] {
    $slave eval namespace delete $ns
}
foreach v [$slave eval info vars] {
    $slave eval unset $v
}
foreach cmd [$slave eval info commands] {
    # Note: we're hiding, not completely removing
    $slave hide $cmd
}

# Make the aliases for the things we want
foreach cmd {f1 f2 f3} {
    $slave alias $cmd $cmd
}

# And evaluate the untrusted script in it
catch {$slave invokehidden source $theScript}

# Finally, kill the untrusted interpreter
interp delete $slave
Run Code Online (Sandbox Code Playgroud)

  • 您还可能希望定义一个`unknown`命令,以便您可以更好地处理未定义的命令,但这是可选的. (2认同)