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

Arg as code in a function

Started by Waterspark63, 24 July 2018 - 07:05 AM
Waterspark63 #1
Posted 24 July 2018 - 09:05 AM
So I am trying to make a Yes/No menu function, and I am trying to get it so one or more of the args in the function call allows a different line of code, so for example:


function YesNo(a,B)/>
    print("Do you want to continue?")
    print("Y/N:")
    write(" ")
    local answer = read()
    if answer == "Yes" then
	    print("Ok. Continuing.")
	    (Somehow put arg one here)
    elseif answer == "No" then
	    ("Ok, Canceling.")
	    (Somehow arg two here)
    end
end
print("Delete system32?")
YesNo(fs.delete("system32"), os.reboot())


Main reason is so I can reuse the same YesNo function with different results based on the context of the situation
Bomb Bloke #2
Posted 24 July 2018 - 11:28 AM
You could handle it like this, by bundling up your function pointers and parameters into tables, and then passing those in:

function YesNo(a, b)
    print("Do you want to continue?")
    print("Y/N:")
    write(" ")
    local answer = read()
    if answer == "Yes" then
            print("Ok. Continuing.")
            a[1](unpack(a, 2))
    elseif answer == "No" then
            ("Ok, Canceling.")
            b[1](unpack(b, 2))
    end
end
print("Delete system32?")
YesNo({fs.delete, "system32"}, {os.reboot})

But to my mind, it'd be a lot easier and neater to have your YesNo function simply return a bool:

function YesNo(msg)
    if msg then print(msg) end
    print("Do you want to continue?")
    print("Y/N:")
    write(" ")
    local answer = read()
    if answer == "Yes" then
            print("Ok. Continuing.")
            return true
    elseif answer == "No" then
            ("Ok, Canceling.")
            return false
    end
end

if YesNo("Delete system32?") then fs.delete(system32) else os.reboot() end
Edited on 24 July 2018 - 09:29 AM
IliasHDZ #3
Posted 31 July 2018 - 11:48 AM
Use functions as arguments:


function YesNo(a,B)/>/>
    print("Do you want to continue?")
    print("Y/N:")
    write(" ")
    local answer = read()
    if answer == "Yes" then
		    print("Ok. Continuing.")
            a() -- here is the argument function getting executed. you can add arguments in here as well.
    elseif answer == "No" then
		    ("Ok, Canceling.")
		    B() -- same thing with the a arg function.
    end
end
print("Delete system32?")

function deleteSys()
    fs.delete("system32")
end

YesNo(deleteSys, os.reboot)

--[[ You will have to remove the parenthesis.
The function gets executed in the "YesNo" function. this means the args get inserted there as well ]]

This should work.