Skip to content

Instantly share code, notes, and snippets.

@omni5cience
Forked from graue/gist:5079734
Last active December 14, 2015 11:39
Show Gist options
  • Save omni5cience/5080679 to your computer and use it in GitHub Desktop.
Save omni5cience/5080679 to your computer and use it in GitHub Desktop.

NOTE: Scroll down for explanation (the difference turns out to be scoping, not closures per se).

$ cat juices.lua
local fruits = {"apple", "orange", "grape"}
local juicers = {}

for i,v in ipairs(fruits) do
    local fruit = v
    juicers[i] = function() return fruit .. " juice" end
end

print(juicers[1]());
print(juicers[2]());
print(juicers[3]());
$ lua juices.lua 
apple juice
orange juice
grape juice
$ cat juices.js
var fruits = ["apple", "orange", "grape"];
var juicers = [];

for (var i in fruits) {
    var fruit = fruits[i];
    juicers[i] = function() { return fruit + " juice"; }
}

console.log(juicers[0]());
console.log(juicers[1]());
console.log(juicers[2]());
$ node juices.js
grape juice
grape juice
grape juice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment