Jump to content




Arg as code in a function


2 replies to this topic

#1 Waterspark63

  • Members
  • 13 posts

Posted 24 July 2018 - 08: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

#2 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 24 July 2018 - 10: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 by Bomb Bloke, 24 July 2018 - 10:29 AM.


#3 IliasHDZ

  • Members
  • 6 posts
  • LocationMechelen, Antwerp, Belgium

Posted 31 July 2018 - 10: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users