'Helper function to load a table definition by its name'

@classmethod
def table(cls, tablename, default=None, db_only=False):

    s3 = current.response.s3
    if (s3 is None):
        s3 = current.response.s3 = Storage()
    s3db = current.s3db
    models = current.models
    if (not db_only):
        if (tablename in s3):
            return s3[tablename]
        elif ((s3db is not None) and (tablename in s3db.classes)):
            (prefix, name) = s3db.classes[tablename]
            return models.__dict__[prefix].__dict__[name]
    db = current.db
    found = None
    if hasattr(db, tablename):
        return ogetattr(db, tablename)
    elif (ogetattr(db, '_lazy_tables') and (tablename in ogetattr(db, '_LAZY_TABLES'))):
        return ogetattr(db, tablename)
    else:
        (prefix, name) = tablename.split('_', 1)
        if (prefix == DYNAMIC_PREFIX):
            try:
                found = S3DynamicModel(tablename).table
            except AttributeError:
                pass
        elif hasattr(models, prefix):
            module = models.__dict__[prefix]
            loaded = False
            generic = []
            for n in module.__all__:
                model = module.__dict__[n]
                if hasattr(model, '_s3model'):
                    if loaded:
                        continue
                    if hasattr(model, 'names'):
                        if (tablename in model.names):
                            model(prefix)
                            loaded = True
                        else:
                            continue
                    else:
                        generic.append(n)
                elif (n == tablename):
                    s3db.classes[tablename] = (prefix, n)
                    found = model
                    loaded = True
            if (not loaded):
                [module.__dict__[n](prefix) for n in generic]
    if found:
        return found
    if ((not db_only) and (tablename in s3)):
        return s3[tablename]
    elif hasattr(db, tablename):
        return ogetattr(db, tablename)
    elif (ogetattr(db, '_lazy_tables') and (tablename in ogetattr(db, '_LAZY_TABLES'))):
        return ogetattr(db, tablename)
    elif isinstance(default, Exception):
        raise default
    else:
        return default
