Im creating a drop-down menu which loops through some objects, creating a menuItem control for each object. All menuItem controls have a command with a lambda function - which takes the iterator value as argument.
import pymel.core as pm
def myMenu(menu):
# Delete popup menu contents, as we need to rebuild...
menu.deleteAllItems()
# Mesh or components selected?
sel = pm.filterExpand( selectionMask=(12, 31, 32, 34, 35) )
if sel != [] and sel != None:
# Get object list and active obj
objList, someObj = funcA()
if objList != [] and objList != None:
# Rebuild the textScrollList
for item in objList:
# Create menuItem
pm.menuItem(
command=lambda *args: funcB(someObj, item), # Problem here
label=item,
parent=menu
)
# Create default button
pm.menuItem(
command=lambda *args: funcC(someObj),
label="Default",
parent=menu
)
else: # No mesh is selected
pm.menuItem(
enable=False,
label="No mesh selected",
parent=menu
)
Problem is commented in the middle of the code (# problem here).
Instead of getting say, three menuItem with commands that pass item1, item2 and item3 as variables, every single menuItem gets the last data that was inside the iterator.
I thought that lambda/anonymous functions would get the variable data that you feed them right there and now (ie: when an object with a lambda function has been created - the stuff inside the function wont change). The actual labels of these menuItem controls do get the correct names though.
Can someone explain this behavior?