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

Add-In applications to program

Started by lifewcody, 23 July 2016 - 11:27 PM
lifewcody #1
Posted 24 July 2016 - 01:27 AM
Hi there! I am working on a base OS for my project and the ENTIRE thing is based on being able to drag and drop 'applications' into the folder (or download them) restart the computer and it then integrates into the system. The issue I am having is the files have multiple functions and I don't think loadstring() works on multiple functions.


Current code:

local apps = fs.list(appDir)
for k, v in pairs(apps) do
  local file = fs.open(appDir .. "/" .. v, "r")
  table["applications"][v] = loadstring(file.readAll())()
  file.close()
  print("LOADED " .. v)
  table["applications"][v]()
  
end

There are multiple functions in the file it loaded. I want to be able to call table["applications"]["app"].startup() or .myOtherFunc()
KingofGamesYami #2
Posted 24 July 2016 - 01:37 AM
Best way seems to be the way non-cc APIs are created; you simply return the table.


return {
  function startup()

  end,

  function myOtherFunc()

  end
}

And loading:

for k, v in pairs(apps) do
  local file = fs.open(appDir .. "/" .. v, "r")
  table["applications"][v] = loadstring(file.readAll())() --#note: DO NOT ACTUALLY USE table AS A VARIABLE NAME.  EVER.
  file.close()
  print("LOADED " .. v)
  table["applications"][v].startup() --#SERIOUSLY DON'T DO THIS.  IT WILL NOT BE GOOD.
  table["applications"][v].myOtherFunc()
end
lifewcody #3
Posted 24 July 2016 - 01:40 AM
Best way seems to be the way non-cc APIs are created; you simply return the table.


return {
  function startup()

  end,

  function myOtherFunc()

  end
}

And loading:

for k, v in pairs(apps) do
  local file = fs.open(appDir .. "/" .. v, "r")
  table["applications"][v] = loadstring(file.readAll())() --#note: DO NOT ACTUALLY USE table AS A VARIABLE NAME.  EVER.
  file.close()
  print("LOADED " .. v)
  table["applications"][v].startup() --#SERIOUSLY DON'T DO THIS.  IT WILL NOT BE GOOD.
  table["applications"][v].myOtherFunc()
end

Thanks, I didn't actually use a variable name as table, I just had to replace it because what I had was super duper long. As for the .startup() what is the reason to not do that?

EDIT: Also, is there a way to do it without return?
Edited on 23 July 2016 - 11:41 PM
KingofGamesYami #4
Posted 24 July 2016 - 02:04 AM
That was just another comment about not using 'table' as a variable name.

And yes, obviously there is a way to do this without return or the table. If you just want to remove return, you can concat return while loading it.
 loadstring( "return " .. file.readAll() )

If you want to get rid of the table entirely, you'll end up doing something similar to os.loadAPI. While this makes it much easier to write programs (literally just write the functions like you'd do for an API), it's not as easy to implement.