Announcement

Collapse
No announcement yet.

Using array as function parameter

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Using array as function parameter

    I used this code to do the job:

    Code:
    function sample(par1, par2, par3)
    	pars = {par1, par2, par3};
    	for key, value in pairs (pars) do
    	    Dialog.Message("Notice", value, MB_OK, MB_ICONINFORMATION, MB_DEFBUTTON1);
    	end 
    end
    And it works fine but I think there must be a better way to do this, because parameters may increase or decrease during using the function.

    Any one to help out

  • #2
    Code:
    function sample(pars)
    	if(type(pars) ~= "table")then
    		error("argument #1: table expected, got " .. type(pars), 2);
    	end
    
    	for key, value in pairs(pars) do
    		Dialog.Message("Notice", value, MB_OK, MB_ICONINFORMATION, MB_DEFBUTTON1);
    	end 
    end
    
    local t = {"Hello", "World!!", "Tables", "are", "awesome."};
    sample(t);
    Bas Groothedde
    Imagine Programming :: Blog

    AMS8 Plugins
    IMXLH Compiler

    Comment


    • #3
      Thank you very much

      Comment


      • #4
        This one also works

        PHP Code:
        function sample(...)
            for 
        keyvalue in ipairs (arg) do
                
        Dialog.Message("Notice"valueMB_OKMB_ICONINFORMATIONMB_DEFBUTTON1);
            
        end
        end
        sample
        (1,2,3,4,5,6

        Comment


        • #5
          Yes, but you then cannot store the multiple values in a table beforehand, unless you use unpack.
          Bas Groothedde
          Imagine Programming :: Blog

          AMS8 Plugins
          IMXLH Compiler

          Comment


          • #6
            Thanks both of you. I have a little question: What is the difference between pairs and ipairs?

            Comment


            • #7
              ipairs fetches the array-like indexes in an array (numeric) and pairs iterates over all keys.

              - http://www.luafaq.org/#T1.10

              Google is your best friend.
              Bas Groothedde
              Imagine Programming :: Blog

              AMS8 Plugins
              IMXLH Compiler

              Comment

              Working...
              X