Jump to content




API function variables with other functions?


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

#1 Waitdev_

  • Members
  • 432 posts
  • LocationAdelaide

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?

#2 Creator

    Mad Dash Victor

  • Members
  • 2,168 posts
  • LocationYou will never find me, muhahahahahaha

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


#3 Bomb Bloke

    Hobbyist Coder

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

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.





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users