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

Namespaces in Computercraft

Started by marczone3, 14 August 2013 - 02:16 AM
marczone3 #1
Posted 14 August 2013 - 04:16 AM
Hello,

I am working on a small project and i have a question i could actually find no information on. Is there a way to create new namespaces? Like the namespace main inside a program. So that i could call the function like: main.loadQuerryRedstone()

Greets,

Marc
Lyqyd #2
Posted 14 August 2013 - 08:47 PM
Split into new topic.

They're not namespaces per se, but actually tables. You'd just create a new table and put functions in it:


local main = {}
function main.loadQuarryRedstone()
  --do stuff
end

You can, of course, fill the table with its functions at time of declaration, but for that, you use a slightly different form:


main = {
  loadQuarryRedstone = function()
    --do stuff
  end,
}
theoriginalbit #3
Posted 15 August 2013 - 03:46 AM
It should also be noted that when you load APIs with
os.loadAPI("filename")
that file will then be loaded into the global environment for use by your programs in the same syntax as Lyqyd posted above (as it's a table in the environment). Example:

Usage

os.loadAPI("someApiFile")

someApiFile.bar()

someApiFile

--# NOTE: this function (or anything marked with `local` is not accessible by external programs! (or any other scope that is outside of the one it is declared in)
local function foo()
  print("foo")
end

--# NOTE: This is a publicly accessible function that can be accessed with fileName.bar()
function bar()
  foo()
  print("bar")
end
marczone3 #4
Posted 15 August 2013 - 04:41 PM
Thanks to both of you for pointing that out. I knew that they were stored in tables so that was not the issue, but i forgot to create the table itself.

Am I understanding this right:

API:

main= {}

function main.groof()
   --Do something
end

Main Code:

os.loadAPI("API")
API.main.goof()

Should work?
theoriginalbit #5
Posted 15 August 2013 - 04:46 PM
indeed that should work :)/>