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

API function variables with other functions?

Started by Waitdev_, 25 November 2015 - 09:35 AM
Waitdev_ #1
Posted 25 November 2015 - 10:35 AM
its hard to explain, so i'll explain it with some code.
when it uses:

example = api.something("param")
example.addSomething("somethingElse") --how do i do things with the variable
example.doStuff("stuff") --like dis?
basically, if an api has a function which returns something, how can it have functions connected to it? is there a tutorial or wiki page on it?
Creator #2
Posted 25 November 2015 - 10:39 AM
in the api:

function fomething(param)
	 --locals here like: local wow = 3
    local self = { --public functions here
		  addSomething = function(morewow) wow =  morewow end,
		  doStuff = function() end
	 }
	 return self
end
Bomb Bloke #3
Posted 25 November 2015 - 10:54 AM
A decent understanding of scope is required to see how that works.

In the above, every time you call fomething() a new variable "wow" is generated as local to that instance of the function call. That variable will persist in memory until about the time nothing refers to it, at which point it becomes eligible for garbage collection..

Normally, variables localised to a function would lose their references when the function call ended. But in the above case, new functions have been generated within the "self" table, which fomething() returned: So "wow" sticks around in memory until the "self" table (and more to the point, the function pointers inside the table) have been discarded. Those functions can continue to work with and manipulate "wow".

It's important to note that every time you call fomething(), a new instance of the function goes onto the function stack, and a new version of "wow" gets generated. Each "self" table fomething() returns will hence point to a unique version of "wow".

The source for the vector and window APIs contain examples. The vector API is especially interesting, as it uses metatables to use one copy of the functions in the "vector" table for all vector objects it returns; see here for some reading on that technique. Keep in mind how colon notation works, too.