Jump to content




Namespaces in Computercraft


  • You cannot reply to this topic
4 replies to this topic

#1 marczone3

  • Members
  • 4 posts

Posted 14 August 2013 - 03: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

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 14 August 2013 - 07: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,
}


#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 15 August 2013 - 02: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


#4 marczone3

  • Members
  • 4 posts

Posted 15 August 2013 - 03: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?

#5 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 15 August 2013 - 03:46 PM

indeed that should work :)





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users