Back to Recipes Homepage
recipe picture
Recipe: Field length
3.666665
Your rating: None Average: 3.7 (3 votes)
Used 141 times with an average impact of -5627 points.

Profile

Name: Field length
ID: 2692
Created on: Thu, 06/10/2010 - 07:12
Updated on: Thu, 06/10/2010 - 07:12
Description:

When dealing with tables, this function checks how many elements are in the list. Works also on empty lists and returns 0 then.



Best For


Comments

Joined: 09/18/2009
Groups: SETI.Germany
That's how the code does look like

function get_field_length(field) -- checks how many entries are in a list
l=1
k=0
while (l~=nil) do
k=k+1
l=field[k]
end -- while
return (k-1)
end -- function

field={1,3,2,5,4}
FL=get_field_length(field)
print("Field length is ",FL)

Tlaloc's picture
User offline. Last seen 5 weeks 4 days ago. Offline
Joined: 08/04/2008
Groups: Mojo Risin'
Easier way to do this

field = {1, 3, 2, 5, 4}
print('Field length is ', #field)

This works for most tables.

2.5.5 - The Length Operator

The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).

The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

Want to try?
Add to Cookbook!
To download recipes to your cookbook, you need to have the game client running.
Parent

none

Children

none

Authors
Sitemap

Developed by: UW Center for Game Science, UW Institute for Protein Design, Northeastern University, Vanderbilt University Meiler Lab, UC Davis
Supported by: DARPA, NSF, NIH, HHMI, Amazon, Microsoft, Adobe, RosettaCommons