This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
MetalMiner's profile picture

[Lua]

Started by MetalMiner, 22 September 2012 - 08:40 AM
MetalMiner #1
Posted 22 September 2012 - 10:40 AM
Hi

Is it possible to execute a string?
I want to do something like this:

command = 'print("Hello")'
Now, I'm searching for a command wich executes this string…
I tried it with

loadstring(command)
but i don't know exactly what it does, and it didn't worked.

thanks
sjele #2
Posted 22 September 2012 - 10:54 AM
This way is pretty bad, as it allso says . unknown file. or whatever the msg for a unexsisting file is. anyways here is the code


command  = print("Hello World")
shell.run(command)
ardera #3
Posted 22 September 2012 - 12:17 PM
Ok, Here is a little tutorial about loadstring:

The only thing that loadstring does, is converting a string into a binary function you can run.

so if you do

str='print("Hello")'

then you can run it as a function as following:

loadstring(str)()

you can also make a function like:


function dostring(str)

	loadedstring=loadstring(str) --loads the string, loadedstring is now a function

	loadedstring() --this will run the function

end

and sjele:

I'm really sure that your code won't work.

Look in the bios.lua and you will see that nearly all os functions are self made,
no uncopiable functions like in the fs API.
sjele #4
Posted 22 September 2012 - 12:19 PM
it did work when i did shell.run it tho. Atleast in the CC emu. Output from my code:
hello world
no such program
Fatal_Exception #5
Posted 22 September 2012 - 12:51 PM
This way is pretty bad, as it allso says . unknown file. or whatever the msg for a unexsisting file is. anyways here is the code


command  = print("Hello World")
shell.run(command)

This doesn't work. All you're doing is running print("Hello World") and assigning it's return value to command.

Output of:

command = print("Hello World")
print(command)

is:

Hello World
1

So you're calling shell.run(1)
ardera #6
Posted 23 September 2012 - 10:00 AM
@Fatal_Exception: Right. ^^

@sjele:

you're calling the function print if you do print().
You copy a function or get its variable if you do variable=print
Then you can do variable("hello") and it will print hello.

And he wanted to run a string, and not run a fully new function.

@Metalminer:

If you want to run a string like a program, that has no access to your variables, you can do:

str='print("hello")'
str=loadstring(str)
setfenv(str, _G) --sets the environment of the function to the _G table
str()

There are also a lot of useful global functions, like getfenv, setmetatable, getmetatable, (and much more) nearly nobody uses…